<?php

namespace app\index\controller;

use think\Controller;
use think\Session;
use think\Request;
use think\View;
use think\Db;
use app\index\validate\Valid;
use PHPExcel;
use PHPExcel_Writer_Excel5;
use PHPExcel_Style_Alignment;
use PHPExcel_Style_Fill;
use PHPExcel_Style_Border;
use PHPExcel_Cell_DataType;
class TiApply extends Commonti
{
    //补录销量操作
    public function addjizhun(){
         $request = Request::instance();


        $data = $request->post();
       // print_r($data);exit;
        $pro=explode(',',$data["pstr"]);
        $projian=implode(',',array_unique($pro));
        $prolist=Db::table("pro_products")->where("id in ($projian)")->select();
        $net=explode(',',$data["nstr"]);
        $kao=explode(',',$data["kstr"]);
        $val=explode(',',$data["vstr"]);
        $add=[];
        for($i=0;$i<count($pro);$i++){
            $tmp["cuser"]=Session::get("employee_id");$tmp["puser"]=Session::get("employee_id");
            $tmp["ctime"]=time();$tmp["ptime"]=time();$tmp["pro_id"]=$pro[$i];$tmp["jxs_id"]=$data["jid"];
            $tmp["net_id"]=$net[$i];
            $tmp["kaoheqi2"]=$kao[$i];
            for($j=0;$j<count($prolist);$j++){
                if($pro[$i]==$prolist[$j]["id"]){
                     $tmp["sn"]=$prolist[$j]["pro_no"]; $tmp["name"]=$prolist[$j]["pro_name"];$tmp["unit"]=$prolist[$j]["unit"];
                     $tmp["num"]=round($val[$i]*$prolist[$j]["box_num"]);
                     break;
                 }
            }
            $add[]=$tmp;
        }
        try{
            $res1=Db::table("cg_net_basic")->insertAll($add);
        }catch (\Exception $e) {
            return 2;
        }
        if($res1)
            return 1;
        else
            return 2;
    }
    //补录销量
    public function bulu(){
         $request = Request::instance();


        $data = $request->get();
        $jid=$data["jid"];
         $pros=$data["pros"];
        $nets=$data["net"];
        $start=strtotime($data["start"]);
        $end=strtotime($data["end"]);
        $kaohes=Db::Table("cg_kaoheqi2")->where("starttime<=$end and endtime>=$start")->field("id,title")->select();
         //print_r($kaohes);exit;
         $karr=[];
        for($i=0;$i<count($kaohes);$i++){
            $karr[]=intval($kaohes[$i]["title"]);
        }
        $kaos=implode(',',$karr);
         $has=Db::table("cg_net_basic")->where("pro_id in ($pros) and net_id in ($nets) and kaoheqi2 in ($kaos)")
        ->select();
        $proarr=Db::table("pro_products")->alias("pp")
        ->join("pro_sku ps","pp.sku_id=ps.id")
        ->where("pp.id in ($pros)")
        ->field("ps.sku_no,ps.sku_name,pp.pro_no,pp.pro_name,pp.id")->select(); 

        $netarr=Db::table("cg_net")->where("id in ($nets)")->select();
        $needs=[];
        for($j=0;$j<count($netarr);$j++){
            for($i=0;$i<count($proarr);$i++){
                for($k=0;$k<count($karr);$k++){
                    $tmp=["pro_id"=>$proarr[$i]["id"],"sku_no"=>$proarr[$i]["sku_no"],"sku_name"=>$proarr[$i]["sku_name"],
                    "pro_no"=>$proarr[$i]["pro_no"],"pro_name"=>$proarr[$i]["pro_name"],
                    "net_id"=>$netarr[$j]["id"],"net_name"=>$netarr[$j]["title"],"net_no"=>$netarr[$j]["sn"],"kaoheqi2"=>$karr[$k]];
                    $needs[]=$tmp;
                }
            }
        }
         
        for($i=count($needs)-1;$i>=0;$i--){
            $flag=0;
            for($j=0;$j<count($has);$j++){

                if($has[$j]["pro_id"]==$needs[$i]["pro_id"]&&$has[$j]["net_id"]==$needs[$i]["net_id"]&&$has[$j]["kaoheqi2"]==$needs[$i]["kaoheqi2"]){

                    $flag=1;break;
                }
            }
            if($flag==1)
                array_splice($needs, $i,1);
           
        }
        $pnarr=[];
        $kaohearr=[];
        $pndet=[];
        for($i=0;$i<count($needs);$i++){
            $pnstr=$needs[$i]["pro_id"]."_".$needs[$i]["net_id"];
            if(!in_array($pnstr,$pnarr)){
                $pnarr[]=$pnstr;
                $pndet[]=$needs[$i];
            }
            if(!in_array($needs[$i]["kaoheqi2"],$kaohearr))
                $kaohearr[]=$needs[$i]["kaoheqi2"];
        }
        sort($kaohearr);
       // print_r($pnarr);
        $this->assign("pndet",$pndet);
        $this->assign("kaohearr",$kaohearr);
        $this->assign("needs",$needs);
        $this->assign("jid",$jid);
        return $this->fetch();
    }
    //核对基准
    public function heduijizhun(){

        $request = Request::instance();


        $data = $request->post();
       
        $pros=$data["pro"];
        $nets=$data["net"];
        $start=strtotime($data["start"]);
        $end=strtotime($data["end"]);
        $kaohes=Db::Table("cg_kaoheqi2")->where("starttime<=$end and endtime>=$start")->field("id,title")->select();
         //print_r($kaohes);exit;
         $karr=[];
        for($i=0;$i<count($kaohes);$i++){
            $karr[]=intval($kaohes[$i]["title"]);
        }
        $kaos=implode(',',$karr);
        $num=Db::table("cg_net_basic")->where("pro_id in ($pros) and net_id in ($nets) and kaoheqi2 in ($kaos)")
        ->count();
        $cp=count(explode(',',$pros));$cn=count(explode(',',$nets));$ck=count($kaohes);
        if($num==$cp*$cn*$ck)
            return 1;
        else
            return 2;
    }
    //申请详细
    public function apply_de($aid)
    {

        $apply = Db::table("cg_ti")->alias("ap")
            ->join("cg_ti yuan", "ap.old=yuan.id", "LEFT")
            ->join("cg_ti next", "ap.new=next.id", "LEFT")
            ->join("ti_state s", "ap.status=s.id")
            ->join("employee ec", "ap.cuser=ec.id", "LEFT")
            ->join("job_employee je", "ec.id=je.employee_id", "LEFT")
            ->join("job j", "je.job_id=j.id", "LEFT")
            ->join("department_employee de", "ec.id=de.employee_id", "LEFT")
            ->join("department d", "de.department_id=d.id", "LEFT")
            ->join("cg_jxs jx", "ap.jxs_id=jx.id")
            ->join("cg_market_zoning jz", "jx.zoning=jz.id", "LEFT")
            ->join("cg_market_provice jp", "jx.provice=jp.id", "LEFT")
            ->join("cg_market_city jc", "jx.city=jc.id", "LEFT")
            ->where(["ap.id" => $aid, "de.index" => 1])
            ->field("ap.title,ap.sn as no,yuan.sn as yuanno,next.sn as nextno,yuan.id as yuanid,next.id as nextid,s.title as zhuangtai,ec.em_name as cname,j.job_name,d.de_name,ap.ctime as created_on,jx.title as jingxiao,jz.title as fenqu,jp.title as sheng,jc.title as shi,yuan.status2 as yuantag,ap.status2 as nowtag,ap.status2 as tag,ap.fb is_fankui,ap.status,jx.id as jxs_id,ap.cate_id")
            ->find();
        $apply["created_on"] = date("Y-m-d", $apply["created_on"]);
        $this->assign("apply", $apply);//["apply_id" => $aid, "type" => 0, "is_deleted" => 0, "is_actived" => 1,"state" => 7]
        $fb = Db::table("all_ti_feeback_list")->where("apply_id=$aid and type=0 and is_deleted=0 and is_actived=1 and state not in (8,9)")->find();
        $hx = Db::table("cg_ti_hexiao")->alias("h")->join("cg_ti_hexiao_list hl", "hl.hx_id=h.id")->where("hl.ti_id=$aid and status not in (8,9)")->group("h.id")->field("h.id,h.sn")->select();
        $flagfb = 0;
        if ($fb)
            $flagfb = 1;
        $flaghx = 0;
        if ($hx)
            $flaghx = 1;
        $this->assign("fb", $fb);
        $this->assign("flagfb", $flagfb);
        $this->assign("hx", $hx);
        $this->assign("flaghx", $flaghx);
        $applynet = Db::table("cg_ti")->query("select apd.net_id,sum(apd.boxnum) as sellnums,sum(apd.bucha) as buchas,sum(apd.amount) as zonges,sum(apd.pizhunweishui) as pifuzonges,sum(fb_shijiweishui) as fankuijines,sum(apd.pizhunhanshui) as hanshuis,sum(apd.fb_hanshui) as fankuihanshuis,sum(fb_shijitourufeiyong) as fb_shijitourufeiyongs,sum(yjsjtrfy) as yjsjtrfys,sum(apd.totalExpectedSales) as xiaoshoues,sum(fb_boxnum) as fannums,sum(apd.fb_shijixiaoliang) as fanxiaoshoues,(sum(fb_boxnum)/sum(apd.boxnum)*100) as dachenglv,sum(apd.hx_yihexiao) as hexiaos,sum((apd.yuan_price-apd.now_price)*p.box_num*apd.bucha) as jxscha,sum((apd.wangdian_yuan-apd.wangdian_price)*p.box_num*apd.bucha) as netcha,sum(apd.hanshui*apd.yujiroi)/sum(apd.hanshui) as yujirois from cg_ti as ap inner join cg_ti_list as apd on apd.ti_id=ap.id inner join pro_products as p on apd.product=p.id where ap.id=$aid  group by apd.net_id");
          $all = ["sellnums" => 0, "xiaoshoues" => 0, "buchas" => 0, "zonges" => 0, "hanshuis" => 0,"jxscha"=>0,"netcha"=>0,"feiyonglv"=>0,"yujirois"=>0,"fannums"=>0,
            "fanxiaoshoues"=>0,"hexiaos"=>0,"pifuzonges"=>0,"fankuijines"=>0,"fankuihanshuis"=>0,"yjsjtrfys"=>0,"fb_shijitourufeiyongs"=>0
          ];
            for ($i = 0; $i < count($applynet); $i++) {
                $all["sellnums"] += $applynet[$i]["sellnums"];
                $all["xiaoshoues"] += $applynet[$i]["xiaoshoues"];
                $all["buchas"] += $applynet[$i]["buchas"];
                $all["zonges"] += $applynet[$i]["zonges"];
                $all["hanshuis"] += $applynet[$i]["hanshuis"];
                $all["jxscha"]+=$applynet[$i]["jxscha"];
                $all["netcha"]+=$applynet[$i]["netcha"];
                $applynet[$i]["feiyonglv"]=$applynet[$i]["hanshuis"]/$applynet[$i]["xiaoshoues"]*100;
                $all["yujirois"]=$all["hanshuis"]*$applynet[$i]["yujirois"];
                $all["fannums"]+=$applynet[$i]["fannums"];
                $all["fanxiaoshoues"]+=$applynet[$i]["fanxiaoshoues"];
                $all["hexiaos"]+=$applynet[$i]["hexiaos"];
                 $all["pifuzonges"] += $applynet[$i]["pifuzonges"];
                  $all["fankuijines"] += $applynet[$i]["fankuijines"];
                  $all["fankuihanshuis"] += $applynet[$i]["fankuihanshuis"];
                  if($applynet[$i]["yjsjtrfys"])
                    $all["yjsjtrfys"] += $applynet[$i]["yjsjtrfys"];
                if($applynet[$i]["fb_shijitourufeiyongs"])
                    $all["fb_shijitourufeiyongs"] += $applynet[$i]["fb_shijitourufeiyongs"];
            }
            $all["feiyonglv"]=$all["hanshuis"]/$all["xiaoshoues"]*100;
            $all["yujirois"]=$all["yujirois"]/$all["hanshuis"];
            $all["dachenglv"]=$all["fannums"]/ $all["sellnums"]*100;
            $this->assign("all",$all);
            $this->assign("netnum",count($applynet));
        $this->assign("applynet", $applynet);
        $net_num = count($applynet);
        $this->assign("net_num", $net_num);

        $applyde = Db::table("cg_ti")->alias("ap")
            ->join("cg_ti_list apd", "apd.ti_id=ap.id")
            ->join("cg_ti_list yuanapd", "apd.refer_id=yuanapd.id", "LEFT")
            ->join("cg_net n", "apd.net_id=n.id", "LEFT")
            ->join("cg_system s", "n.system_id=s.id", "LEFT")
            ->join("pro_products p", "apd.product=p.id")
            ->join("pro_sku sk", "p.sku_id=sk.id")
            ->join("pro_series ps", "sk.series_id=ps.id")
            ->join("pro_price pp", "pp.pid=p.id")
            ->join("cg_feiyongkemu3 f3", "apd.feetype=f3.id")
            ->join("cg_paymethod cp", "apd.paymethod=cp.id")
            ->join("cg_fijiru cf", "apd.project=cf.id")
            ->join("cg_fijiruzd fj", "apd.jrbm=fj.id")->join("department d", "fj.title=d.id")
            ->where(["ap.id" => $aid])->order("apd.net_id,apd.product")
            ->field("ap.sn as no,apd.sn as detail_no,apd.net_id,apd.id as did,apd.is_bu,n.title as net,s.title as xitong,ps.series_name,p.pro_name,apd.start as start_time,apd.end as end_time,apd.expCanTime as  hexiao_time,apd.boxnum as sell_num,apd.bucha,p.unit,p.box_num,pp.factory,apd.yuan_price,apd.now_price,apd.wangdian_price,apd.lingshou_price,apd.huodong_price,f3.title as feiyong3,apd.amount as zonge,(apd.pizhunhanshui) as hanshui,apd.brief as beizhu,apd.head as fuzeren,cp.title as zffs,cf.title as jrfa,(apd.totalExpectedSales) as xiaoshoue,apd.feiyongmiaoshu as remark,d.de_name,apd.shuilv,apd.fb_shuilv,apd.isVAT as dikou,apd.fb_isVAT as dikou1,apd.zhejia,apd.hx_yihexiao as hexiao,apd.paymethod as zfid,apd.status as tag,yuanapd.start  as yuanstart,yuanapd.end as yuanend,yuanapd.expCanTime as yuanhexiao,apd.ydreason,apd.cancel_reason,apd.fb_shijixiaoliang as fankuinum,(apd.fb_shijixiaoliang) as shijixiaoshoue,(apd.fb_boxnum/apd.boxnum)*100 as xiaoliang,(apd.wangdian_price*apd.zhejia/100) as zj,(apd.wangdian_price-apd.wangdian_price*apd.zhejia/100) as wangcuxiao,(apd.wangdian_price*apd.zhejia/100)*p.box_num*apd.fb_shijixiaoliang as zjzj,yuanapd.yjsjtrfy as yuanzonge,apd.pizhunweishui as  pifuzonge,apd.fb_shijiweishui as fankuijine,apd.fb_hanshui as fankuihanshui,apd.fb_shijitourufeiyong,apd.yjsjtrfy,apd.yujifeiyonglv,apd.jizhunboxnum as totalBenchmarkSales,apd.yujiroi,apd.zhejia,apd.wangdian_zhejia,((apd.yuan_price-apd.now_price)*p.box_num*apd.bucha) as jxscha,apd.maoli,apd.wangdian_yuan,((apd.wangdian_yuan-apd.wangdian_price)*p.box_num*apd.bucha) as netcha,apd.netout,apd.huodongout,apd.fb_boxnum")
            ->select();

        for ($i = 0; $i < count($applyde); $i++) {
            $applyde[$i]["start_time"] = date("Y-m-d", $applyde[$i]["start_time"]);
            $applyde[$i]["end_time"] = date("Y-m-d", $applyde[$i]["end_time"]);
            $applyde[$i]["hexiao_time"] = date("Y-m-d", $applyde[$i]["hexiao_time"]);
            if ($applyde[$i]["yuanstart"])
                $applyde[$i]["yuanstart"] = date("Y-m-d", $applyde[$i]["yuanstart"]);
            if ($applyde[$i]["yuanend"])
                $applyde[$i]["yuanend"] = date("Y-m-d", $applyde[$i]["yuanend"]);
            if ($applyde[$i]["yuanhexiao"])
                $applyde[$i]["yuanhexiao"] = date("Y-m-d", $applyde[$i]["yuanhexiao"]);
        }
        //print_r($applyde);
        $this->assign("applyde", $applyde);

        //费用支付方式
        $fipay = db('cg_paymethod')->field('id,title')->select();
        $this->assign('fipay', $fipay);
        $this->assign("aid", $aid);
        //费用类型
        $feiyongjine=Db::table("cg_ti")->alias("ap")
            ->join("cg_ti_list apd", "apd.ti_id=ap.id")
            ->join("cg_feiyongkemu3 f3", "apd.feetype=f3.id")
            ->where(["ap.id" => $aid])
            ->group("f3.id,apd.feetype")
            ->field("f3.title,sum(apd.pizhunhanshui) as jine")
            ->select();
        $this->assign("feiyongjine",$feiyongjine);
        $logs=$this->getlog($aid);
        $this->assign("logs",$logs);
        return $this->fetch();
    }

    //审核模拟申请
    public function shapply($aid)
    {
        $updata["id"] = $aid;
        $sq = Db::table("cg_ti")->where(["id" => $aid])->find();
        if ($sq["cate_id"] == 1) {
            $updata["status"] = 7;
            Db::startTrans();
            try {
                $res = Db::table("cg_ti_list")->query("update cg_ti_list set pizhunweishui=amount,pizhunhanshui=hanshui where ti_id=$aid");
                $res1 = Db::Table("cg_ti")->update($updata);
            } catch (\Exception $e) {
                Db::rollBack();
                return 2;
            }
            if ($res1) {
                Db::commit();
                return 1;
            } else
                return 2;
        } else if ($sq["cate_id"] == 3) {
            //审批取消
            $updata["status"] = 7;
            Db::startTrans();
            try {
                $res1 = Db::table("cg_ti")->update($updata);
                //原单取消
                $yuan = $sq["old"];
                $new = $aid;
                //原单剩余组成新单
                $shanchulist = Db::table("cg_ti_list")->where(["ti_id" => $aid])->field("refer_id")->select();
                $list = [];
                for ($i = 0; $i < count($shanchulist); $i++) {
                    $list[] = $shanchulist[$i]["refer_id"];
                }
                $liststr = implode(',', $list);
                //获得剩余
                $shengyu = Db::table("cg_ti_list")->where("ti_id=$yuan and id not in ($liststr)")->select();

                if ($shengyu) {
                    $newsq = $sq;
                    $newsq["status"] = 7;
                    $newsq["status2"] = null;
                    $newsq["cate_id"] = 1;
                    $newsq["old"] = $yuan;
                    $newsq["sn"] = $this->produceSN();
                    unset($newsq["id"]);

                    $res3 = Db::table("cg_ti")->insertGetId($newsq);
                    // echo $res3;exit;
                    $new = $res3;
                    $newadd = [];
                    for ($i = 0; $i < count($shengyu); $i++) {
                        $tmp = $shengyu[$i];
                        $tmp["ti_id"] = $res3;
                        $tmp["sn"] = $i + 1;
                        unset($tmp["id"]);
                        $newadd[] = $tmp;
                    }
                    //print_r($newadd);exit;
                    $res4 = Db::table("cg_ti_list")->insertAll($newadd);

                } else {
                    $res3 = 1;
                    $res4 = 1;
                }
                $res2 = Db::table("cg_ti")->where(["id" => $yuan])->update(["status2" => 2, "new" => $new]);
            } catch (\Exception $e) {
                Db::rollBack();
                return 2;
            }
            if ($res1 && $res2 && $res3 && $res4) {
                Db::commit();
                return 1;
            } else
                return 2;

        } else {
            //异动申请
            $updata["status"] = 7;
            Db::startTrans();
            try {
                //本单通过
                $res = Db::table("cg_ti_list")->query("update cg_ti_list set pizhunweishui=amount,pizhunhanshui=hanshui where ti_id=$aid");
                $res1 = Db::table("cg_ti")->update($updata);
                $yuan = $sq["old"];
                $res2 = Db::table("cg_ti")->where(["id" => $yuan])->update(["status2" => 1, "new" => $aid]);
            } catch (\Exception $e) {
                Db::rollBack();
                return 2;
            }
            if ($res1 && $res2) {
                Db::commit();
                return 1;
            } else
                return 2;
        }


    }

    //列表
    public function index($page=1,$list=20)
    {
        //获取类型列表

        $request = Request::instance();


        $data = $request->post();
        $eid=Session::get("employee_id");
        $where = "ap.type_id=2 and ap.cuser=$eid ";
        if ($data) {
            if ($data["no"])
                $where .= "and ap.sn={$data["no"]} ";
            if (trim($data["title"]))
                $where .= "and ap.title like '%{$data["title"]}%' ";
            if ($data["status"])
                $where .= "and ap.status={$data["status"]} ";
            if (trim($data["start"])) {
                $st = strtotime($data["start"]);
                $where .= "and ap.ctime>=$st ";
            }
            if (trim($data["end"])) {
                $ed = strtotime($data["end"]) + 24 * 3600;
                $where .= "and ap.ctime<$ed ";
            }
        } else {
            $data = ["no" => "", "title" => "", "status" => "", "start" => "", "end" => ""];
        }
        $sum=Db::table("cg_ti")->alias("ap")
            ->join("cg_ti yuan", "ap.old=yuan.id", "LEFT")
            ->join("cg_ti_cate cc", "ap.cate_id=cc.id")
            ->join("employee ec", "ap.cuser=ec.id", "LEFT")
            ->where($where)->count();
             $maxpage=ceil($sum/$list);
        $page=$page<$maxpage?$page:$maxpage;
        $page=$page>1?$page:1;

        $start=($page-1)*$list;
        $applys = Db::table("cg_ti")->alias("ap")
            ->join("cg_ti yuan", "ap.old=yuan.id", "LEFT")
            ->join("cg_ti_cate cc", "ap.cate_id=cc.id")
            ->join("employee ec", "ap.cuser=ec.id", "LEFT")
            ->where($where)
            ->order("ap.ctime desc,ap.id desc")->limit($start,$list)
            ->field("ap.id,ap.sn,ap.title,ap.status,ap.status2,ec.em_name as cname,ap.ctime,ap.fb,ap.cate_id,ap.sfxyfk,ap.is_ydqx")
            ->select();
        for ($i = 0; $i < count($applys); $i++) {
            switch ($applys[$i]["status"]) {

                case 2:
                    $applys[$i]["status_type"] = "已打回";
                    break;
                case 3:
                    $applys[$i]["status_type"] = "区域领导审批";
                    break;
                case 4:
                    $applys[$i]["status_type"] = "拆分人审批";
                    break;
                case 5:
                    $applys[$i]["status_type"] = "集团领导审批";
                    break;
                case 6:
                    $applys[$i]["status_type"] = "抄送";
                    break;
                case 7:
                    $applys[$i]["status_type"] = "已归档";
                    break;
                case 8:
                    $applys[$i]["status_type"] = "已作废";
                    break;
                case 9:
                    $applys[$i]["status_type"] = "已否决";
                    break;
                default:
                    $applys[$i]["status_type"] = "草稿";
                    break;
            }
            $applys[$i]["ctime"] = date("Y-m-d", $applys[$i]["ctime"]);
            $fbnum = Db::table("cg_ti_list")->where(["ti_id" => $applys[$i]["id"], "hx_status" => 3])->count();
            //p($fbnum);
            if ($fbnum)
                $applys[$i]["kefan"] = 1;
            else
                $applys[$i]["kefan"] = 0;
            $henum = Db::table("cg_ti_list")->where(["ti_id" => $applys[$i]["id"], "hx_status" => 0])->count();
            if ($henum)
                $applys[$i]["kehe"] = 1;
            else
                $applys[$i]["kehe"] = 0;

            $yihenu = Db::table("cg_ti_hexiao_list")->where(["ti_id" => $applys[$i]["id"]])->count();
            if ($yihenu)
                $applys[$i]["yihe"] = 1;
            else
                $applys[$i]["yihe"] = 0;
        }
        $this->assign("applys", $applys);
        //p($applys);

        $this->assign("data", $data);
        $this->assign("sum",$sum);
        $this->assign("page",$page);
        $this->assign("list",$list);
        $this->assign("maxpage",$maxpage);

        return $this->fetch();
    }
    public function zuofeichuli(){
        $request = Request::instance();$data = $request->post();
        //print_r($data);exit;
        $fid=3;$aid=$data["aid"];
        
            $res=$this->goworker($fid,$aid,$data["nodeKey"],$data["selectId"],$data["selectName"]);
           // print_r($res);exit;
            if($res["operateStatus"]=="success"){
                $ydid=Db::table("yusuan")->alias("y")->join("yusuan_detail yd","yd.yid=y.id")->where("yd.aid=$aid and y.type=1")->field("yd.id")->select();
                if($ydid){
                    $ydids=[];
                    for($i=0;$i<count($ydid);$i++){
                        $ydids[]=$ydid[$i]["id"];
                    }
                    $yd=implode(',',$ydids);
                    Db::table("yusuan_detail")->query("update yusuan_detail set type=0 where id in ($yd)");
                }
                    try{
                        
                           
                            $up["id"]=$aid;
                            $up["status"]=8;
                        Db::table("cg_ti")->update($up);
                    }catch (\Exception $e){
        
                          return json_encode(["msg"=>"系统繁忙请稍后再试","state"=>2]);
                        }
                      return json_encode(["msg"=>"","state"=>1]);
                  
                     
                }else{
                return json_encode(["msg"=>"系统繁忙请稍后再试","state"=>2]);
                }
      
        
    }
    //新增申请
    public function addform($aid = 0,$from=1)
    {
        $this->assign("from",$from);
        $fujian = [];
        if ($aid) {
            $apply = Db::table("cg_ti")->alias("ap")
                ->join("cg_jxs j", "ap.jxs_id=j.id")
                ->where(["ap.id" => $aid])->field("ap.id,ap.sn,ap.jxs_id,ap.is_notice,ap.brief as remark,ap.title,j.title as jxs,ap.attach as annex_id,status")
                ->find();
            $this->assign("apply", $apply);
            //附件
            if ($apply["annex_id"])
                $fujian = Db::table("annex")->where("id in({$apply["annex_id"]})")->select();
             if($apply["status"]==2){
                    $btn=$this->getbton(3,$aid);
                    $this->assign("btn",$btn);
                    $logs=$this->getlog($aid);
                    //print_r($logs);
                    $this->assign("logs",$logs);
                }

            $applynet = Db::table("cg_ti")->query("select apd.net_id,sum(apd.boxnum) as sellnums,sum(apd.bucha) as buchas,sum(apd.amount) as zonges,sum(apd.hanshui) as hanshuis,sum(apd.totalExpectedSales) as xiaoshoues,sum((apd.yuan_price-apd.now_price)*p.box_num*apd.bucha) as jxscha,sum((apd.wangdian_yuan-apd.wangdian_price)*p.box_num*apd.bucha) as netcha,sum(apd.hanshui*apd.yujiroi)/sum(apd.hanshui) as yujirois from cg_ti as ap inner join cg_ti_list as apd on apd.ti_id=ap.id inner join pro_products as p on apd.product=p.id where ap.id=$aid  group by apd.net_id ");

            
            $all = ["sellnums" => 0, "xiaoshoues" => 0, "buchas" => 0, "zonges" => 0, "hanshuis" => 0,"jxscha"=>0,"netcha"=>0,"feiyonglv"=>0,"yujirois"=>0];
            for ($i = 0; $i < count($applynet); $i++) {
                $all["sellnums"] += $applynet[$i]["sellnums"];
                $all["xiaoshoues"] += $applynet[$i]["xiaoshoues"];
                $all["buchas"] += $applynet[$i]["buchas"];
                $all["zonges"] += $applynet[$i]["zonges"];
                $all["hanshuis"] += $applynet[$i]["hanshuis"];
                $all["jxscha"]+=$applynet[$i]["jxscha"];
                $all["netcha"]+=$applynet[$i]["netcha"];
                $applynet[$i]["feiyonglv"]=$applynet[$i]["hanshuis"]/$applynet[$i]["xiaoshoues"]*100;
                $all["yujirois"]=$all["hanshuis"]*$applynet[$i]["yujirois"];
            }
            $all["feiyonglv"]=$all["hanshuis"]/$all["xiaoshoues"]*100;
            $all["yujirois"]=$all["yujirois"]/$all["hanshuis"];
            $this->assign("applynet", $applynet);
            $applyde = Db::table("cg_ti")->alias("ap")
                ->join("cg_ti_list apd", "apd.ti_id=ap.id")
                ->join("cg_net n", "apd.net_id=n.id", "LEFT")
                ->join("cg_system s", "n.system_id=s.id", "LEFT")
                ->join("pro_products p", "apd.product=p.id")
                ->join("pro_sku sk", "p.sku_id=sk.id")
                ->join("pro_series ps", "sk.series_id=ps.id")
                ->join("pro_price pp", "pp.pid=p.id")
                ->join("cg_feiyongkemu3 f3", "apd.feetype=f3.id")
                ->join("cg_paymethod cp", "apd.paymethod=cp.id")
                ->join("cg_fijiru cf", "apd.project=cf.id")
                ->join("cg_fijiruzd fj", "apd.jrbm=fj.id")->join("department d", "fj.title=d.id")
                ->where(["ap.id" => $aid])->order("apd.net_id,apd.product")
                ->field("ap.sn as no,apd.sn as detail_no,apd.net_id,apd.id as did,apd.is_bu,n.title as net,s.title as xitong,ps.series_name,p.pro_name,apd.start as start_time,apd.end as end_time,apd.expCanTime as hexiao_time,apd.boxnum as sell_num,apd.bucha,p.unit,p.box_num,pp.factory,apd.yuan_price,apd.now_price,apd.wangdian_price,apd.lingshou_price,apd.huodong_price,f3.title as feiyong3,apd.amount as zonge,apd.hanshui,apd.brief as beizhu,apd.head as fuzeren,cp.title as zffs,cf.title as jrfa,(apd.totalExpectedSales) as xiaoshoue,apd.feiyongmiaoshu as remark,d.de_name,apd.shuilv,apd.isVAT as dikou,apd.yujifeiyonglv,apd.totalBenchmarkSales,apd.yujiroi,apd.zhejia,apd.wangdian_zhejia,((apd.yuan_price-apd.now_price)*p.box_num*apd.bucha) as jxscha,apd.maoli,apd.wangdian_yuan,((apd.wangdian_yuan-apd.wangdian_price)*p.box_num*apd.bucha) as netcha,apd.netout,apd.huodongout,apd.jizhunboxnum")
                ->select();
            for ($i = 0; $i < count($applyde); $i++) {
                $applyde[$i]["start_time"] = date("Y-m-d", $applyde[$i]["start_time"]);
                $applyde[$i]["end_time"] = date("Y-m-d", $applyde[$i]["end_time"]);
                $applyde[$i]["hexiao_time"] = date("Y-m-d", $applyde[$i]["hexiao_time"]);
            }
            $this->assign("applyde", $applyde);
            //print_r($applyde);exit;
            
        } else {
            $all = ["sellnums" => 0, "xiaoshoues" => 0, "buchas" => 0, "zonges" => 0, "hanshuis" => 0,"jxscha"=>0,"netcha"=>0,"feiyonglv"=>0,"yujirois"=>0];
        }

        $this->assign("all", $all);
        $this->assign("aid", $aid);
        $this->assign("fujian", $fujian);
        return $this->fetch();
    }

    //suggest查找网点
    public function netjson2($jid)
    {
        $sys=db("cg_system_jxs")->where("jxs_id=$jid and isdel=0")->column("system_id");
        if($sys){
            $sys=implode(',',$sys);
            $data=db("cg_net")->where("system_id in ($sys)")->field("title,id")->select();
        }else{
            $data=[];
        }
        /*
        $data = Db::table('cg_net')->alias("n")
            ->join("cg_system s", "n.system_id=s.id")
            ->join("cg_jxs j", "s.jxs=j.id")
            ->where("j.id=$jid")
            ->field('n.title,n.id')->select();*/

        echo json_encode(['message' => 'ok', 'value' => $data, 'code' => '200', 'redirect' => '']);
    }

    //选择单品
    public function selectProduct($jid)
    {
        $this->assign("jid", $jid);
        return $this->fetch();
    }

    public function selectProduct2($jid)
    {
        $this->assign("jid", $jid);
        return $this->fetch();
    }

    //选择网点
    public function selectNet()
    {
        return $this->fetch();
    }

    public function selectNet2()
    {
        return $this->fetch();
    }

    //按照经销商返回网点树
    public function netTree()
    {
        $jid = $this->request->param('keyword');
        $where = [];
        $sys=db("cg_system_jxs")->where("jxs_id=$jid and isdel=0")->column("system_id");
        if($sys){
            $sys=implode(',',$sys);
            $data = db('cg_system')->where("id in ({$sys}) and isdel=0")
            ->field('id,title name')
            ->select();
            foreach ($data as $k => $v) {
                # code...
                $net=db("cg_net")->where("system_id={$v["id"]} and isdel=0")->field("id,title name")->select();
                $data[$k]['children'] = $net;
            }
        }else{
            $data=[];
        }
       
        echo json_encode($data);
    }

    public function addData()
    {
        $request = Request::instance();


        $data = $request->get();
        $aid = $data["aid"];
        $jid = $data["jxs"];
        $this->assign("jid", $jid);
        //费用支付方式
        $fipay = db('cg_paymethod')->field('id,title')->select();
        $this->assign('fipay', $fipay);

        //费用计入方案
        $fipay = db('cg_fijiru')->field('id,title')->select();
        $this->assign('fijiru', $fipay);

        //获取优惠费用类型
        $where['esuseway'] = ['like', '%"9"%'];
        //$where["tejiabuchatype"] = 10;
        $youhui = db("cg_feiyongkemu3")->where($where)->select();
        $this->assign("aid", $aid);
        $this->assign("youhui", $youhui);

        $eid=Session::get("employee_id");
        $euser=Db::table("employee")->where(["id"=>$eid])->find();
        $this->assign("eu_name",$euser["em_name"]);
        return $this->fetch();
    }
 //suggest查找费用科目3
    public function feiyongkemu3json(){
          $esuseway = $this->request->param('esuseway');
        $where = [];
        if($esuseway){
            $where['esuseway'] = ['like','%"'.$esuseway.'"%'];
        }
        $data = Db::table('cg_feiyongkemu3')->field('title,id')->where($where)->select();
//        echo Db::table('cg_feiyongkemku3')->getLastSql();
        echo json_encode(['message'=>'ok','value'=>$data,'code'=>'200','redirect'=>'']);
    }
    //添加费用
    public function addFeiyong()
    {
        //费用支付方式
        $fipay = db('cg_paymethod')->field('id,title')->select();
        $this->assign('fipay', $fipay);

        //费用计入方案
        $fijiru = db('cg_fijiru')->field('id,title')->select();
        $this->assign('fijiru', $fijiru);

        $str = '';
        foreach ($fipay as $k => $v) {
            $str .= '<option value="' . $v['id'] . '">' . $v['title'] . '</option>';
        }
        $str2 = '';
        foreach ($fijiru as $k => $v) {
            $str2 .= '<option value="' . $v['id'] . '">' . $v['title'] . '</option>';
        }

        $name = 'a' . mt_rand();
        echo <<<EOF
 <tr class="feiyongxiang">
            <td> 
            	 <div class="container-fluid">
                        <div class="row">
                            <div class="col-xs-8">
                                <div class="input-group" >
                                    <input type="text" placeholder="请输入关键字或空格查询" class="form-control feetype" name="feetype[]" value="">
                                    <div class="input-group-btn">
                                        <button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown">
                                            <span class="caret"></span>
                                        </button>
                                        <ul class="dropdown-menu dropdown-menu-right" role="menu">
                                        </ul>
                                    </div>
                                </div>
                                <div class="selectedOnlyOne " style="display:none;" >

                                    <span class="inin"></span>
                                    <span class="close">×</span>
                                </div>
                            </div>
                            <div class="col-xs-4">
                                <button  class="btn btn-primary feetree" type="button" >选择</button>
                            </div>
                        </div>
                    </div>
                </td>
            <td><input type="text" name="zonge[]" class="form-control zonge num2"></td>
            <td>
                <select name="paymethod[]"  class="form-control paymethod">
                        <option value="">请选择</option>
                       {$str}
                    </select>  
            </td>
             <td>
				 <div class="container-fluid">
                        <div class="row">
                            <div class="col-xs-8">
                                <div class="input-group" >
                                    <input type="text" placeholder="请输入关键字或空格查询" class="form-control jrbm" name="jrbm[]" value="">
                                    <div class="input-group-btn">
                                        <button type="button" type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown">
                                            <span class="caret"></span>
                                        </button>
                                        <ul class="dropdown-menu dropdown-menu-right" role="menu">
                                        </ul>
                                    </div>
                                </div>
                                <div class="selectedOnlyOne " style="display:none;" >
                                    <span class="inin">f111</span>
                                    <span class="close">×</span>
                                </div>
                            </div>
                            <div class="col-xs-4">
                                <button class="btn btn-primary select_jrbm" type="button" >选择</button>
                            </div>
                        </div>
                    </div>
             </td>
             <td>
                <select name="project[]" class="form-control project">
                        <option value="">请选择</option>
                         {$str2}
                    </select>   
            </td>
            <td><input type="text" name="remark[]" class="form-control"></td> 
             <td class="text-center"><button class="btn btn-danger del_fi_item" type="button">删除</button> </td>
        </tr>
EOF;

    }

    //获取产品内容
    public function getpro($id, $jid = 0)
    {
        if ($id) {
            $arr = Db::table("pro_products")->alias("p")
                ->join("pro_price pp", "pp.pid=p.id")
                ->where("p.id=$id")
                ->field("p.id,p.pro_name,p.box_num,p.unit,pp.factory,pp.sell_standard,pp.availability,pp.retail_low,pp.retail_high,pp.promotion_high,pp.promotion_low")
                ->find();
            $gp = Db::table("price_group_product")->alias("pgp")
                ->join("price_group_jxs pgj", "pgp.gid=pgj.gid", "LEFT")
                ->where("pgj.jid=$jid and pgp.pid=$id")
                ->field("pgp.lingshou_price")->find();
            $price = "";
            if ($arr["factory"])
                $price = $arr["factory"];
            if ($gp)
                $price = $gp["lingshou_price"];
            echo <<<EOF
 		<tr class="infoContent protrs"  proid="{$arr["id"]}">
 			<input type="hidden" value="{$arr["id"]}" name="pid[]"/>
            <td><span class="productText">{$arr["pro_name"]}</span><a href="javascript:;"><span class="glyphicon glyphicon-eye-open eyes" aria-hidden="true" title="产品详情" onclick="prodetail({$arr["id"]})"></span></a></td>
            <td><span>{$arr["box_num"]}</span>{$arr["unit"]}/箱</td>
            <td><input type="text" class="form-control boxs num2" name="boxs[]" value="0.00" style="min-width: 70px;width: 70px">箱</td>
            <td>{$arr["factory"]}元/{$arr["unit"]}</td>
            <td><input type="text" class="form-control num2" style="min-width: 70px;width: 70px" readonly name="yuanjsx[]" value="{$price}">元/{$arr["unit"]}</td>
             <td>
             折价率:<input type="text" class="form-control jxszhejia num2" style="min-width: 70px;width: 70px" name="jxszhejia[]"  value="0.00">% OFF<br/>
             现供价:<input type="text" class="form-control xianjsx num2" style="min-width: 70px;width: 70px" name="xianjsx[]"  value="{$price}">元/{$arr["unit"]}<br/>
             毛利率:<input type="text" class="form-control jxsmao num2" name="jxsmao[]" style="min-width: 70px;width: 70px"  value="-100.00">%

             </td>
              <td><input type="text" class="form-control netyuan num2" style="min-width: 70px;width: 70px" name="wangdianfei[]" value="">元/{$arr["unit"]}</td>
            <td>
                折价率:<input type="text" class="form-control netzhejia num2" style="min-width: 70px;width: 70px" name="netzhejia[]" value="0.00">% OFF<br/>
                现供价:<input type="text" class="form-control xiannet num2" style="min-width: 70px;width: 70px" name="xiannet[]"  value="0.00">元/{$arr["unit"]}<br/>
                毛利率:<input type="text" class="form-control netmao num2" name="netmao[]" style="min-width: 70px;width: 70px"   value="0.00">%
                 <input type="hidden" name="nethigh[]" value="{$arr["retail_high"]}"/><input type="hidden" name="netlow[]" value="{$arr["retail_low"]}"/>
            </td>
             <td><input type="text" class="form-control chabox num2" style="min-width: 70px;width: 70px" name="chabox[]">箱</td>
            <td><input type="text" class="form-control yuanp num2" style="min-width: 70px;width: 70px" name="yuanp[]" value="{$arr["sell_standard"]}">元/罐</td>
            <td><input type="text" class="form-control xianp num2" style="min-width: 70px;width: 70px" name="xianp[]" value="{$arr["sell_standard"]}">元/罐
                <input type="hidden" name="cuxiaohigh[]" value="{$arr["promotion_high"]}"/><input type="hidden" name="cuxiaolow[]" value="{$arr["promotion_low"]}"/>
            </td>
            <input type="hidden" name="boxunit[]" value="{$arr["box_num"]}"/>
        </tr>
EOF;

        } else {
            return 0;
        }
    }

    //获取2月以后
    public function gettwomon($datet)
    {
        $date_two = date("Y/m/d", strtotime("$datet +3 month"));
        return $date_two;
    }

    public function prodetail($pid)
    {

        $pro = Db::table("pro_products")->alias("p")
            ->join("pro_sku sk", "p.sku_id=sk.id", "LEFT")
            ->join("pro_series s", "sk.series_id=s.id", "LEFT")
            ->join("pro_category c", "s.category_id=c.id", "LEFT")
            ->join("pro_brands b", "c.brand_id=b.id", "LEFT")
            ->join("pro_price pp", "pp.pid=p.id", "LEFT")
            ->join("pro_entry e", "p.entry=e.id", "LEFT")
            ->join("cg_channel_types2 c2", "p.channel_type=c2.id", "LEFT")
            ->join("cg_channel_types1 c1", "c2.pid=c1.id", "LEFT")
            ->where(["p.id" => $pid])
            ->field("p.pro_name,p.pro_no,sk.sku_no,sk.sku_name,s.series_name,c.category_name,b.brand_name,p.pro_sku,e.entry_name,c1.title as channel1,c2.title as channel2,p.format,p.unit,p.box_num,p.box_weight,p.box_volume,p.weight,p.box_size,pp.factory,pp.box_factory,pp.cost,pp.box_cost,pp.availability,pp.box_availability,pp.retail_standard,pp.box_retail_standard,pp.retail_low,pp.box_retail_low,pp.retail_high,pp.box_retail_high,pp.sell_standard,pp.box_sell_standard,pp.sell_low,pp.box_sell_low,pp.sell_high,pp.box_sell_high,pp.promotion_shocking,pp.box_promotion_shocking,pp.promotion_low,pp.box_promotion_low,pp.promotion_high,pp.box_promotion_high,p.remark,p.sheji,p.dingwei,p.wenhua,p.maidian,p.gongneng,p.tongxilie")
            ->find();
        if ($pro["box_cost"])
            $factmao = round(($pro["box_factory"] - $pro["box_cost"]) / $pro["box_cost"] * 100, 2) . '%';
        else
            $factmao = "-";
        if ($pro["box_retail_standard"]) {
            $lingshoumao = round(($pro["box_retail_standard"] - $pro["box_factory"]) / $pro["box_retail_standard"] * 100, 2) . '%';
        } else {
            $lingshoumao = "-";
        }
        if ($pro["box_sell_standard"] && $pro["box_retail_standard"]) {
            $erjimao = round(($pro["box_sell_standard"] - $pro["box_retail_standard"]) / $pro["box_sell_standard"] * 100, 2) . '%';
        } else {
            $erjimao = "-";
        }
        $this->assign("erjimao", $erjimao);
        $this->assign("lingshoumao", $lingshoumao);
        $this->assign("factmao", $factmao);
        $this->assign("pro", $pro);
        return $this->fetch();
    }

    public function produceSN()
    {
        //生成编号
        $max = db('cg_ti')->where('sn', 'like', date('Ymd') . '%')->max('sn'); //编号递增开始位置基础

        if ($max) {
            $max = (double)$max;
            $insert_sn = $max + 1;
        } else {
            $insert_sn = date('Ymd') . '0001';
        }
        return $insert_sn;
    }

    //生成反馈sn
    public function producefbSN()
    {
        //生成编号
        $max = db('all_ti_feeback_list')->where('no', 'like', date('Ymd') . '%')->max('no'); //编号递增开始位置基础

        if ($max) {
            $max = (double)$max;
            $insert_sn = $max + 1;
        } else {
            $insert_sn = date('Ymd') . '0001';
        }
        return $insert_sn;
    }

    //创建申请
    public function addapply()
    {
        $request = Request::instance();


        $data = $request->post();

        if ($data) {
            //print_r($data);exit;
            if (trim($data["theme"])) {
                $adddata["title"] = htmlspecialchars(trim($data["theme"]));
            } else {
                return json_encode(["wrong" => "主题不能为空", "aid" => ""]);
            }
            if ($data["jxs_id"]) {
                $adddata["jxs_id"] = $data["jxs_id"];

            } else {
                return json_encode(["wrong" => "必须选择经销商", "aid" => ""]);
            }

            if ($data["attach"]) {
                $adddata["attach"] = $data["attach"];
            }
            $adddata["cuser"] = Session::get("employee_id");
            $adddata["puser"] = Session::get("employee_id");
            $adddata["ctime"] = time();
            $adddata["ptime"] = time();
            $adddata["arealat"] = 2;
            $adddata["productlat"] = 5;
            $adddata["status"] = 1;
            $adddata["fb"] = 0;
            $adddata["type_id"] = 2;
            if (isset($data["is_notice"]))
                $adddata["is_notice"] = 1;
            //生成单号

            $adddata["sn"] = $this->produceSN();

            Db::startTrans();
            try {
                $res1 = Db::table("cg_ti")->insertGetId($adddata);


                //$res2=1;
            } catch (\Exception $e) {
                Db::rollBack();
                return json_encode(["wrong" => "系统繁忙请稍后再试", "aid" => ""]);
            }
            if ($res1) {
                Db::commit();
                return json_encode(["wrong" => "", "aid" => $res1]);
            } else {
                Db::rollBack();
                return json_encode(["wrong" => "系统繁忙请稍后再试", "aid" => ""]);
            }
        } else {
            return json_encode(["wrong" => "请正确提交", "aid" => ""]);
        }
    }

    //插入明细
    public function addapplydetail()
    {
        
        $request = Request::instance();


        $data = $request->post();
       // print_r($data);exit;
      // return json_encode(["msg" => $data["youhuiwho"], "state" => "2"]);
        if ($data) {

            //数据处理
            if ($data["nets"]) {
                $netsarr = explode(',', $data["nets"]);
            } else {
                return json_encode(["msg" => "网点不能为空", "state" => "2"]);
            }
            if ($data["pid"]) {
                $prosarr = $data["pid"];
            } else {
                return json_encode(["msg" => "产品不能为空", "state" => "2"]);
            }
            if (!$data["yjverifyTime"])
                return json_encode(["msg" => "预计核销时间不能为空", "state" => "2"]);
            if (!$data["start"])
                return json_encode(["msg" => "促销开始时间不能为空", "state" => "2"]);
            if (!$data["end"])
                return json_encode(["msg" => "促销结束时间不能为空", "state" => "2"]);


            $is_bu = 0;
            $nowday = strtotime(date("Y-m-d"));
            $starttime = strtotime($data["start"]);
            if ($starttime < $nowday)
                $is_bu = 1;
            $endtime=strtotime($data["end"]);
            //查询对应考核期
            $duiyingkaohe=Db::table("cg_kaoheqi2")->where("starttime<=$endtime and endtime>=$starttime")->select();
            $kaohejisuan=[];
            for($i=0;$i<count($duiyingkaohe);$i++){
                $tmp["yue"]=intval($duiyingkaohe[$i]["title"]);
                $tmp["zts"]=($duiyingkaohe[$i]["endtime"]-$duiyingkaohe[$i]["starttime"])/3600/24+1;
                $start=$starttime>=$duiyingkaohe[$i]["starttime"]?$starttime:$duiyingkaohe[$i]["starttime"];
                $end=$endtime<=$duiyingkaohe[$i]["endtime"]?$endtime:$duiyingkaohe[$i]["endtime"];
                $tmp["ts"]=($end-$start)/3600/24+1;
                $kaohejisuan[]=$tmp;
            }
            
            //处理产品数据
            $prolist = [];
            for ($i = 0; $i < count($prosarr); $i++) {
                if ($data["pid"][$i])
                    $prolist[$i]["pro_id"] = $data["pid"][$i];
                else
                    return json_encode(["msg" => "产品不能为空", "state" => "2"]);
                if ($data["boxs"][$i])
                    $prolist[$i]["sell_num"] = $data["boxs"][$i];
                else
                    return json_encode(["msg" => "预计销量不能为空", "state" => "2"]);
                $prolist[$i]["yuan_price"] = $data["yuanjsx"][$i];
                $prolist[$i]["now_price"] = $data["xianjsx"][$i];

                $prolist[$i]["zhejia"]= $data["jxszhejia"][$i];
                if ($data["xiannet"][$i])
                    $prolist[$i]["wangdian_price"] = $data["xiannet"][$i];
                else
                    return json_encode(["msg" => "网点现供货价不能为空", "state" => "2"]);
                if ($data["wangdianfei"][$i])
                    $prolist[$i]["wangdian_yuan"] = $data["wangdianfei"][$i];
                else
                    return json_encode(["msg" => "网点原供货价不能为空", "state" => "2"]);

                $prolist[$i]["wangdian_zhejia"] = $data["netzhejia"][$i];
                $prolist[$i]["bucha"] = $data["chabox"][$i];

                if ($data["yuanp"][$i])
                    $prolist[$i]["lingshou_price"] = $data["yuanp"][$i];
                else
                    return json_encode(["msg" => "原始零售价不能为空", "state" => "2"]);
                if ($data["xianp"][$i])
                    $prolist[$i]["huodong_price"] = $data["xianp"][$i];
                else
                    return json_encode(["msg" => "活动零售价不能为空", "state" => "2"]);

                $prolist[$i]["wangdianmaoli"] = $data["netmao"][$i];
                $prolist[$i]["maoli"] = $data["jxsmao"][$i];
                $pb=Db::table("pro_products")->alias("pp")
                ->join("pro_sku sk","pp.sku_id=sk.id")
                ->join("pro_series ps","sk.series_id=ps.id")
                ->join("pro_category pc","ps.category_id=pc.id")
                ->join("pro_brands pb","pc.brand_id=pb.id")
                ->where("pp.id={$data["pid"][$i]}")
                ->field("pb.profit")->find();
                $prolist[$i]["pbmaoli"]=$pb["profit"];
                $prolist[$i]["netout"]=0;
                //验证范围
                if($data["nethigh"][$i]){
                    if($data["nethigh"][$i]<$data["xiannet"][$i])
                        $prolist[$i]["netout"]=1;
                }
                if($data["netlow"][$i]){
                    if($data["netlow"][$i]>$data["xiannet"][$i])
                        $prolist[$i]["netout"]=1;
                }
                $prolist[$i]["huodongout"]=0;
                if($data["cuxiaohigh"][$i]){
                    if($data["cuxiaohigh"][$i]<$data["xianp"][$i])
                        $prolist[$i]["huodongout"]=1;
                }
                if($data["cuxiaolow"][$i]){
                    if($data["cuxiaolow"][$i]>$data["xianp"][$i])
                        $prolist[$i]["huodongout"]=1;
                }
            }
           // print_r($prolist);exit;
            //费用类型处理
            $feiyonglist = [];
            $fids = [];
            if (isset($_POST["feetype"])) {
                for ($i = 0; $i < count($data["feetype"]); $i++) {
                    if ($data["feetype"][$i])
                        $feiyonglist[$i]["feiyong_id"] = $data["feetype"][$i];
                    else
                        return json_encode(["msg" => "费用编号不能为空", "state" => "2"]);
                    if ($data["zonge"][$i])
                        $feiyonglist[$i]["zonge"] = $data["zonge"][$i];
                    else
                        return json_encode(["msg" => "费用总额必须填写且不能为0", "state" => "2"]);
                    if ($data["paymethod"][$i])
                        $feiyonglist[$i]["zfid"] = $data["paymethod"][$i];
                    else
                        return json_encode(["msg" => "支付方式必须选择", "state" => "2"]);
                    if ($data["jrbm"][$i])
                        $feiyonglist[$i]["jrbm"] = $data["jrbm"][$i];
                    else
                        return json_encode(["msg" => "必须选择费用计入部门", "state" => "2"]);
                    if ($data["project"][$i])
                        $feiyonglist[$i]["fyfa"] = $data["project"][$i];
                    else
                        return json_encode(["msg" => "必须选择费用计入方案", "state" => "2"]);
                    $feiyonglist[$i]["remark"] = $data["remark"][$i];
                    $fids[] = $data["feetype"][$i];
                }
            }

            $fidstr = implode(',', $fids);
            $apply_id = $data["tiapplyid"];
            $aparr = Db::table("cg_ti")->where(['id' => $apply_id])->find();
            $jxs = $aparr["jxs_id"];
            if ($fids) {

                //验证同产品和网点是否有重复
                $issets = Db::table("cg_ti_list")->alias("ap")
                    ->join("pro_products p", "ap.product=p.id")
                    ->join("cg_net n", "ap.net_id=n.id")
                    ->join("cg_feiyongkemu3 k3", "ap.feetype=k3.id")
                    ->where("ap.net_id in ({$data["nets"]}) and ap.product in({$data["pros"]}) and ap.feetype in($fidstr) and ap.ti_id=$apply_id")
                    ->field("n.title as net,p.pro_name,k3.title as feiyong")
                    ->find();

                if ($issets) {
                    return json_encode(["msg" => "网点:{$issets["net"]}中已存在产品:{$issets["pro_name"]}的费用:{$issets["feiyong"]}申请，不可重复", "state" => "2"]);
                }
            }

            //数据混编
            $netcount = count($netsarr);
            $feiyongcount = count($fids);
            $procount = count($prosarr);
            $datalist = [];
            $listnum = 0;
            $numnowdet = Db::table("cg_ti_list")->where(["ti_id" => $apply_id])->max("sn");
            for ($i = 0; $i < $netcount; $i++) {

                //$i循环网点
                for ($j = 0; $j < $procount; $j++) {
                    //计算基准销量
                    $base=0;
                    for($z=0;$z<count($kaohejisuan);$z++){
                        $djizhun=Db::table("cg_net_basic")->where(["pro_id"=>$prolist[$j]["pro_id"],"net_id"=>$netsarr[$i],"kaoheqi2"=>$kaohejisuan[$z]["yue"]])->field("num")->find();
                        $base+=($djizhun["num"]/$kaohejisuan[$z]["zts"]*$kaohejisuan[$z]["ts"]);
                    }

                    //$j循环商品
                    if (($data["youhuiwho"]==1&&$prolist[$j]["zhejia"]>0)||($data["youhuiwho"]==2&&$prolist[$j]["wangdian_zhejia"]>0)) {
                             //return json_encode(["msg" => $prolist[$j]["wangdian_zhejia"], "state" => "2"]);
                        if (!$data["youtype"])
                            return json_encode(["msg" => "渠道折价类型必须选择", "state" => "2"]);
                        if (!$data["jian_paymethod"])
                            return json_encode(["msg" => "支付类型必须选择", "state" => "2"]);
                        if (!$data["sumjian"])
                            return json_encode(["msg" => "未税总额必须填写并且不能为0", "state" => "2"]);
                        if (!$data["jian_jrbm"])
                            return json_encode(["msg" => "费用计入部门必须选择", "state" => "2"]);
                        if (!$data["jian_project"])
                            return json_encode(["msg" => "费用计入方案必须选择", "state" => "2"]);
                        //拥有折价
                        $boxnum = $prolist[$j]["sell_num"] / $netcount / ($feiyongcount + 1);
                        $bucha = $prolist[$j]["bucha"] / $netcount;
                       
                        $yuanp = $prolist[$j]["yuan_price"];
                         if (!$yuanp)
                            $yuanp = null;
                        if($data["youhuiwho"]==1)
                            $youhuizonge = $data["boxunit"][$j] *  $bucha * ( $prolist[$j]["yuan_price"]-$prolist[$j]["now_price"]);
                        else
                            $youhuizonge = $data["boxunit"][$j] *  $bucha * ($prolist[$j]["wangdian_yuan"]-$prolist[$j]["wangdian_price"]);

                        $hanshuis=($youhuizonge + $youhuizonge * 6 / 100);
                        $basee=$base*$prolist[$j]["now_price"]* $data["boxunit"][$j];
                        $yujirois=($boxnum*$prolist[$j]["now_price"]* $data["boxunit"][$j]-$basee)*$prolist[$j]["pbmaoli"]/100;
                        $xiaoshoue=$boxnum*$prolist[$j]["now_price"]* $data["boxunit"][$j];
                        
                        try{
                         $yujirois=$yujirois/$hanshuis;
                         
                        }catch(\Exception $e){
                            $yujirois=0;
                        }
                       
                        //预计费用额/预计销售额
                       $yujifeiyonglv=$hanshuis/($boxnum*$prolist[$j]["now_price"]* $data["boxunit"][$j])*100;

                        $tmp = [
                            "cuser" => Session::get("employee_id"),
                            "puser" => Session::get("employee_id"),
                            "ctime" => time(), "ptime" => time(),
                            "sn" => $listnum + 1 + $numnowdet,
                            "net_id" => $netsarr[$i],
                            "start" => strtotime($data["start"]),
                            "end" => strtotime($data["end"]),
                            "head" => $data["fuzeren"],
                            "expCanTime" => strtotime($data["yjverifyTime"]),
                            "brief" => $data["beizhu"], "feetype" => $data["youtype"],
                            "amount" => $youhuizonge,
                            "pizhunweishui"=>$youhuizonge,
                            "shuilv" => 6,
                            "hanshui" => ($youhuizonge + $youhuizonge * 6 / 100),
                            "pizhunhanshui"=>($youhuizonge + $youhuizonge * 6 / 100),
                            'yjsjtrfy' =>($youhuizonge + $youhuizonge * 6 / 100),
                            "paymethod" => $data["jian_paymethod"],
                            "jrbm" => $data["jian_jrbm"],
                            "project" => $data["jian_project"],
                            "jxs_id" => $jxs,
                            "ti_id" => $apply_id,
                            "product" => $prolist[$j]["pro_id"],
                            "is_bu" => $is_bu,
                            "feiyongmiaoshu" => $data["jian_remark"],
                            "zhejia" => $prolist[$j]["zhejia"],
                            "wangdian_zhejia" => $prolist[$j]["wangdian_zhejia"],
                            "bucha" => $bucha,
                            "totalExpectedSales" => $xiaoshoue,
                            "yuan_price" => $yuanp,
                            "now_price" => $prolist[$j]["now_price"],
                            "wangdian_price" => $prolist[$j]["wangdian_price"],
                            "wangdian_yuan" => $prolist[$j]["wangdian_yuan"],
                            "lingshou_price" => $prolist[$j]["lingshou_price"],
                            "huodong_price" => $prolist[$j]["huodong_price"],
                            "wangdianmaoli" => $prolist[$j]["wangdianmaoli"],
                            "maoli" => $prolist[$j]["maoli"],
                            "totalBenchmarkSales"=>$basee,
                            "yujiroi"=>$yujirois,
                            "yujifeiyonglv"=>$yujifeiyonglv,
                            "hx_status" => 3,
                            "netout"=>$prolist[$j]["netout"],
                            "huodongout"=>$prolist[$j]["huodongout"],
                            "boxnum" => $boxnum,
                            "jizhunboxnum"=>$base
                        ];
                        //echo $tmp["bucha"];
                        $datalist[] = $tmp;

                        $listnum++;
                    } else {
                        $boxnum = $prolist[$j]["sell_num"] / $netcount / ($feiyongcount);
                    }

                    for ($k = 0; $k < $feiyongcount; $k++) {
                        //$k循环费用类型
                        $zonges = $feiyonglist[$k]["zonge"] / $netcount / $procount;
                        $yuanp = $prolist[$j]["yuan_price"];
                          //预计费用额/预计销售额
                        $hanshuis=($zonges + $zonges * 6 / 100);
                       $yujifeiyonglv=$hanshuis/($boxnum*$prolist[$j]["now_price"]* $data["boxunit"][$j])*100;
                       $xiaoshoue=$boxnum*$prolist[$j]["now_price"]* $data["boxunit"][$j];
                       $basee=$base*$prolist[$j]["now_price"]* $data["boxunit"][$j];
                        if (!$yuanp)
                            $yuanp = null;
                        $tmp = [
                            "cuser" => Session::get("employee_id"),
                            "puser" => Session::get("employee_id"),
                            "ctime" => time(), "ptime" => time(),
                            "sn" => $listnum + 1 + $numnowdet,
                            "net_id" => $netsarr[$i],
                            "start" => strtotime($data["start"]),
                            "end" => strtotime($data["end"]),
                            "head" => $data["fuzeren"],
                            "expCanTime" => strtotime($data["yjverifyTime"]),
                            "brief" => $data["beizhu"],
                            "feetype" => $feiyonglist[$k]["feiyong_id"],
                            "amount" => $zonges,
                            "pizhunweishui"=>$zonges,
                            "shuilv" => 6,
                            "hanshui" => ($zonges + $zonges * 6 / 100),
                            "pizhunhanshui"=>($zonges + $zonges * 6 / 100),
                            'yjsjtrfy' =>($zonges + $zonges * 6 / 100),
                              "paymethod" => $feiyonglist[$k]["zfid"],
                            "jrbm" => $feiyonglist[$k]["jrbm"],
                            "project" => $feiyonglist[$k]["fyfa"],
                             "jxs_id" => $jxs, 
                            "ti_id" => $apply_id,
                            "product" => $prolist[$j]["pro_id"],
                            "is_bu" => $is_bu,
                            "feiyongmiaoshu" => $feiyonglist[$k]["remark"],
                             "zhejia" => $prolist[$j]["zhejia"],
                            "wangdian_zhejia" => $prolist[$j]["wangdian_zhejia"],
                            "bucha"=>null,
                            "totalExpectedSales" =>  $xiaoshoue,
                            "yuan_price" => $yuanp,
                            "now_price" => $prolist[$j]["now_price"],
                             "wangdian_price" => $prolist[$j]["wangdian_price"],
                            "wangdian_yuan" => $prolist[$j]["wangdian_yuan"],
                            "lingshou_price" => $prolist[$j]["lingshou_price"],
                            "huodong_price" => $prolist[$j]["huodong_price"],
                             "wangdianmaoli" => $prolist[$j]["wangdianmaoli"],
                            "maoli" => $prolist[$j]["maoli"],
                            "totalBenchmarkSales"=>$basee,
                            "yujiroi"=>($boxnum*$prolist[$j]["now_price"]* $data["boxunit"][$j]-$basee)*$prolist[$j]["pbmaoli"]/100/($zonges + $zonges * 6 / 100),
                            "yujifeiyonglv"=>$yujifeiyonglv,
                            "hx_status" => 3,
                            "netout"=>$prolist[$j]["netout"],
                            "huodongout"=>$prolist[$j]["huodongout"],
                            "boxnum" => $boxnum,
                            "jizhunboxnum"=>$base
                        ];

                        $datalist[] = $tmp;
                        $listnum++;
                    }
                }


            }
            /*for($i=0;$i<count($datalist);$i++){
                echo $datalist[$i]["bucha"]."|";
            }*/
            //print_r($datalist[1]);exit;
           // echo count($datalist);exit;return;
            //储存
           // return;
            Db::startTrans();

            try {


                $res1 = Db::table("cg_ti_list")->insertAll($datalist);


            } catch (\Exception $e) {
                //return $e->getMessage();
                Db::rollBack();
                return json_encode(["msg" => $e->getMessage(), "state" => "2"]);
            }
            if ($res1) {
                Db::commit();
                return json_encode(["msg" => "操作已成功", "state" => "1"]);
            } else {
                Db::rollBack();
                return json_encode(["msg" => "系统繁忙请稍后再试", "state" => "2"]);
            }
        } else {
            return json_encode(["msg" => "系统繁忙请稍后再试", "state" => "2"]);
        }
    }

    //删除明细
    public function shanchu()
    {
        $request = Request::instance();


        $data = $request->post();
        $did = $data["did"];
        $aid = $data["aid"];
        if (!$aid) {
            return 2;
        }
        $ck = Db::table("cg_ti_list")->where(["ti_id" => $aid])->count();
        Db::startTrans();

        try {


            $res1 = Db::table("cg_ti_list")->where("id in($did) and ti_id=$aid")->delete();


        } catch (\Exception $e) {
            //echo $e->getMessage();
            Db::rollBack();
            return 2;
        }
        if ($res1 && $res1 != $ck) {
            Db::commit();
            return 1;
        } else {
            Db::rollBack();
            return 2;
        }
    }

    //修改明细
    public function xiugai($did)
    {
        //费用支付方式
        $fipay = db('cg_paymethod')->field('id,title')->select();
        $this->assign('fipay', $fipay);

        //费用计入方案
        $fipay = db('cg_fijiru')->field('id,title')->select();
        $this->assign('fijiru', $fipay);

        //获取优惠费用类型
        $where['esuseway'] = ['like', '%"9"%'];
       // $where["tejiabuchatype"] = 10;
        $youhui = db("cg_feiyongkemu3")->where($where)->select();

        $this->assign("youhui", $youhui);


        $this->assign("did", $did);
        $detail = Db::table("cg_ti_list")->alias("apd")
            ->join("cg_net n", "apd.net_id=n.id", "LEFT")
            ->join("pro_products p", "apd.product=p.id")
            ->join("pro_price pp", "pp.pid=p.id")
            ->join("cg_feiyongkemu3 f3", "apd.feetype=f3.id")
            ->join("cg_paymethod cp", "apd.paymethod=cp.id")
            ->join("cg_fijiru cf", "apd.project=cf.id")
            ->join("cg_fijiruzd fj", "apd.jrbm=fj.id")->join("department d", "fj.title=d.id")
            ->where(["apd.id" => $did])
            ->field("apd.start as start_time,apd.end as end_time,apd.expCanTime as hexiao_time,apd.head as fuzeren,apd.zhejia,apd.amount as zonge,apd.paymethod as zfid,apd.project as fyfa,apd.brief as beizhu,p.unit,pp.factory,apd.boxnum as sell_num,apd.yuan_price,apd.now_price,apd.wangdian_price,apd.wangdian_yuan,apd.wangdian_zhejia,apd.wangdianmaoli,apd.bucha,apd.lingshou_price,apd.huodong_price,apd.maoli,apd.feiyongmiaoshu as remark,f3.title as zftitle,d.de_name,fj.id as jrbmid,apd.net_id,n.title as netname,apd.product as pro_id,p.pro_name,apd.feetype as feiyong_id,p.box_num,apd.jxs_id,pp.retail_low,pp.retail_high,pp.promotion_high,pp.promotion_low,apd.netout,apd.huodongout")
            ->find();
        $detail["start_time"] = date("Y/m/d", $detail["start_time"]);
        $detail["end_time"] = date("Y/m/d", $detail["end_time"]);
        $detail["hexiao_time"] = date("Y/m/d", $detail["hexiao_time"]);
        $this->assign("detail", $detail);
        return $this->fetch();
    }
    public function xiugaigetp($pid,$jid){
        $arr = Db::table("pro_products")->alias("p")
                ->join("pro_price pp", "pp.pid=p.id")
                ->where("p.id=$pid")
                ->field("p.id,p.pro_name,p.box_num,p.unit,pp.factory,pp.sell_standard,pp.availability,pp.retail_low,pp.retail_high,pp.promotion_high,pp.promotion_low")
                ->find();
            $gp = Db::table("price_group_product")->alias("pgp")
                ->join("price_group_jxs pgj", "pgp.gid=pgj.gid", "LEFT")
                ->where("pgj.jid=$jid and pgp.pid=$pid")
                ->field("pgp.lingshou_price")->find();
            $price = "";
            if ($arr["factory"])
                $price = $arr["factory"];
            if ($gp)
                $price = $gp["lingshou_price"];
            $arr["price"]=$price;
            return json_encode($arr);
    }
    public function selectjrbm()
    {
        return $this->fetch();
    }

    public function selectFee($esuseway)
    {
        $this->assign("esuseway", $esuseway);
        return $this->fetch();
    }

    //费用科目树
    public function feetype3($esuseway)
    {
        $data = Db::table('cg_feiyongkemu1')->field('id,title name')->select();
        foreach ($data as $k => $v) {
            $temp = Db::table('cg_feiyongkemu2')->field('id,title name')->where(array('pid' => $v['id']))->select();
            foreach ($temp as $k1 => $v1) {
                $where['esuseway'] = ['like', '%"' . $esuseway . '"%'];
                $where["pid"] = $v1['id'];
                $temp[$k1]['children'] = Db::table('cg_feiyongkemu3')->field('id,title name')->where($where)->select();
                $temp[$k1]["chkDisabled"] = false;
                $temp[$k1]["nocheck"] = true;
            }
            $data[$k]['children'] = $temp;
            $data[$k]["chkDisabled"] = true;
            $data[$k]["nocheck"] = true;
        }
        echo json_encode($data);
    }

    //修改明细
    public function updatedet()
    {
        $request = Request::instance();


        $data = $request->post();
        if ($data) {
           // print_r($data);exit;
            if ($data["detail"])
                $dataup["id"] = $data["detail"];
            else
                return json_encode(["msg" => "请正确提交", "state" => 2]);

            $yuan = Db::table("cg_ti_list")->where(["id" => $dataup["id"]])->find();
            if ($data["net"])
                $dataup["net_id"] = $data["net"];
            else
                return json_encode(["msg" => "网点不能为空", "state" => 2]);
            if ($data["pro"])
                $dataup["product"] = $data["pro"];
            else
                return json_encode(["msg" => "产品不能为空", "state" => 2]);


            if ($data["start"])
                $dataup["start"] = strtotime($data["start"]);
            else
                return json_encode(["msg" => "活动开始时间不能为空", "state" => 2]);
            if ($data["end"])
                $dataup["end"] = strtotime($data["end"]);
            else
                return json_encode(["msg" => "活动结束时间不能为空", "state" => 2]);
            if ($data["yjverifyTime"])
                $dataup["expCanTime"] = strtotime($data["yjverifyTime"]);
            else
                return json_encode(["msg" => "核销时间不能为空", "state" => 2]);


            if ($data["fuzeren"])
                $dataup["head"] = $data["fuzeren"];
            else
                return json_encode(["msg" => "负责人不能为空", "state" => 2]);
            if ($data["feiyong_id"])
                $dataup["feetype"] = $data["feiyong_id"];
            else
                return json_encode(["msg" => "费用科目必须选择", "state" => 2]);

            if ($data["zonge"])
                $dataup["amount"] = $data["zonge"];
            else
                return json_encode(["msg" => "未税总额必须填写并且不能为0", "state" => 2]);
            $dataup["hanshui"] = $dataup["amount"] + $dataup["amount"] * $yuan["shuilv"] / 100;
            $dataup["pizhunhanshui"]=$dataup["hanshui"];
            $dataup["pizhunweishui"]=$dataup["amount"];
            if ($data["paymethod"])
                $dataup["paymethod"] = $data["paymethod"];
            else
                return json_encode(["msg" => "支付类型必须选择", "state" => 2]);
            if ($data["jrbm"])
                $dataup["jrbm"] = $data["jrbm"];
            else
                return json_encode(["msg" => "计入部门必须选择", "state" => 2]);
            if ($data["project"])
                $dataup["project"] = $data["project"];
            else
                return json_encode(["msg" => "计入部门必须选择", "state" => 2]);
            $dataup["feiyongmiaoshu"] = $data["remark"];
            if ($data["sell_num"])
                $dataup["boxnum"] = $data["sell_num"];
            else
                return json_encode(["msg" => "预计销售额不能为空", "state" => 2]);
            $dataup["bucha"] = $data["bucha"];
            $dataup["yuan_price"]=$data["yuan_price"];
            if ($data["now_price"])
                $dataup["now_price"] = $data["now_price"];
            else
                return json_encode(["msg" => "经销商现供货价不能为空", "state" => 2]);
            $dataup["zhejia"] = $data["zhejia"];
            $dataup["maoli"] = $data["maoli"];
            if ($data["wangdian_yuan"])
                $dataup["wangdian_yuan"] = $data["wangdian_yuan"];
            else
                return json_encode(["msg" => "网点原供货价不能为空", "state" => 2]);
             if ($data["wangdian_price"])
                $dataup["wangdian_price"] = $data["wangdian_price"];
            else
                return json_encode(["msg" => "网点现供货价不能为空", "state" => 2]);
            $dataup["wangdian_zhejia"] = $data["wangdian_zhejia"];
            $dataup["wangdianmaoli"] = $data["wangdianmaoli"];
            if ($data["lingshou_price"])
                $dataup["lingshou_price"] = $data["lingshou_price"];
            else
                return json_encode(["msg" => "网点零售价不能为空", "state" => 2]);
            if ($data["huodong_price"])
                $dataup["huodong_price"] = $data["huodong_price"];
            else
                return json_encode(["msg" => "活动零售价不能为空", "state" => 2]);
            $dataup["brief"] = $data["beizhu"];
            $is_bu = 0;
            $nowday = strtotime(date("Y-m-d"));
            $starttime = $yuan['ctime'];
            if ($starttime < $nowday)
                $is_bu = 1;
            $endtime=strtotime($data["end"]);
            //查询对应考核期
            $duiyingkaohe=Db::table("cg_kaoheqi2")->where("starttime<=$endtime and endtime>=$starttime")->select();
            $kaohejisuan=[];
            for($i=0;$i<count($duiyingkaohe);$i++){
                $tmpt["yue"]=intval($duiyingkaohe[$i]["title"]);
                $tmpt["zts"]=($duiyingkaohe[$i]["endtime"]-$duiyingkaohe[$i]["starttime"])/3600/24+1;
                $start=$starttime>=$duiyingkaohe[$i]["starttime"]?$starttime:$duiyingkaohe[$i]["starttime"];
                $end=$endtime<=$duiyingkaohe[$i]["endtime"]?$endtime:$duiyingkaohe[$i]["endtime"];
                $tmpt["ts"]=($end-$start)/3600/24+1;
                $kaohejisuan[]=$tmpt;
            }
            $dataup["is_bu"] = $is_bu;
            $dataup["ptime"] = time();
            $dataup["puser"] = Session::get("employee_id");
            $dataup["netout"]=0;
            //验证范围
            if($data["nethigh"]){
                if($data["nethigh"]<$data["wangdian_price"])
                    $dataup["netout"]=1;
            }
            if($data["netlow"]){
                if($data["netlow"]>$data["wangdian_price"])
                    $dataup["netout"]=1;
            }
            $dataup["huodongout"]=0;
            if($data["cuxiaohigh"]){
                if($data["cuxiaohigh"]<$data["huodong_price"])
                    $dataup["huodongout"]=1;
            }
            if($data["cuxiaolow"]){
                if($data["cuxiaolow"]>$data["huodong_price"])
                    $dataup["huodongout"]=1;
            }
            //品牌毛利率
            $pb=Db::table("pro_products")->alias("pp")
                ->join("pro_sku sk","pp.sku_id=sk.id")
                ->join("pro_series ps","sk.series_id=ps.id")
                ->join("pro_category pc","ps.category_id=pc.id")
                ->join("pro_brands pb","pc.brand_id=pb.id")
                ->where("pp.id={$data["pro"]}")
                ->field("pb.profit,pp.box_num")->find();
            $pbmaoli=$pb["profit"];
            $boxnum=$pb["box_num"];
            //计算基准销量
            $base=0;
            for($z=0;$z<count($kaohejisuan);$z++){
                $djizhun=Db::table("cg_net_basic")->where(["pro_id"=>$data["pro"],"net_id"=>$data["net"],"kaoheqi2"=>$kaohejisuan[$z]["yue"]])->field("num")->find();
                $base+=($djizhun["num"]/$kaohejisuan[$z]["zts"]*$kaohejisuan[$z]["ts"]);
            }
            $dataup["jizhunboxnum"]=$base;
            $dataup["totalBenchmarkSales"]=$base*$dataup["now_price"]* $boxnum;
            //预计费用率
            $yujifeiyonglv=$dataup["hanshui"]/($boxnum*$dataup["now_price"]* $data["sell_num"])*100;
            $dataup["yujifeiyonglv"]=$yujifeiyonglv;
            //预计roi
            $dataup["yujiroi"]=($boxnum*$dataup["now_price"]* $data["sell_num"]-$dataup["totalBenchmarkSales"])*$pbmaoli/100/$dataup["hanshui"];
            $dataup["totalExpectedSales"]=$boxnum*$dataup["now_price"]* $data["sell_num"];

            $tmp = Db::table("cg_ti_list")->where(["id" => $dataup["id"]])->field("ti_id")->find();

            $issets = Db::table("cg_ti_list")->alias("ap")
                ->join("pro_products p", "ap.product=p.id")
                ->join("cg_net n", "ap.net_id=n.id")
                ->join("cg_feiyongkemu3 k3", "ap.feetype=k3.id")
                ->where("ap.net_id ={$dataup["net_id"]} and ap.product={$dataup["product"]} and ap.feetype={$dataup["feetype"]} and ap.ti_id={$tmp["ti_id"]} and ap.id<>{$dataup["id"]}")
                ->field("n.title as net,p.pro_name,k3.title as feiyong")
                ->find();
            //  print_r($data);exit;
            if ($issets) {
                return json_encode(["msg" => "网点:{$issets["net"]}中已存在产品:{$issets["pro_name"]}的费用:{$issets["feiyong"]}申请，不可重复", "state" => "2"]);
            }
            //print_r($dataup);exit;
            Db::startTrans();

            try {


                $res1 = Db::table("cg_ti_list")->update($dataup);


            } catch (\Exception $e) {
                //echo $e->getMessage();
                Db::rollBack();
                return json_encode(["msg" => "系统繁忙请稍后再试", "state" => 2]);
            }
            if ($res1) {

                Db::commit();


                return json_encode(["msg" => $tmp["ti_id"], "state" => 1]);
            } else {
                Db::rollBack();
                return json_encode(["msg" => "系统繁忙请稍后再试", "state" => 2]);
            }
        } else {
            return json_encode(["msg" => "请正确提交", "state" => 2]);
        }
    }
    public function baocunchuli(){
        $request = Request::instance();
        $data = $request->post();
        if ($data) {
            //print_r($data);exit;
            if ($data["aid"])
                $dataup["id"] = $data["aid"];
            else
                return json_encode(["msg" => "请正确提交", "state" => 2]);
            if ($data["jxs_id"])
                $dataup["jxs_id"] = $data["jxs_id"];
            else
                return json_encode(["msg" => "经销商不能为空", "state" => 2]);
            if ($data["theme"])
                $dataup["title"] = $data["theme"];
            else
                return json_encode(["msg" => "主题不能为空", "state" => 2]);
            $dataup["attach"] = $data["attach"];
            if(isset($data["is_notice"]))
                $dataup["is_notice"] = 1;
            else
                 $dataup["is_notice"]=0;
            $dataup["status"] = 3;
            $dataup["ptime"] = time();
            $dataup["puser"] = Session::get("employee_id");
            Db::startTrans();
            try {
                $ys=$this->tiys($data["aid"]);
                    if($ys===0&&$dataup["status"]==3)
                        return json_encode(["msg" => "尚未设定ti预算格式无法提交", "state" => 2]);
                $res1 = Db::table("cg_ti")->update($dataup);

                $savetype = $dataup["status"];
                if ($savetype == '3') {
                    if($ys){
                        Db::table("yusuan_detail")->insertAll($ys);
                    }
                    
                }

            } catch (\Exception $e) {
                //echo $e->getMessage();
                Db::rollBack();
                return json_encode(["msg" => "系统繁忙请稍后再试", "state" => 2]);
            }
            if ($res1) {
                $fid=3;$aid=$data["aid"];
                $res=$this->goworker($fid,$aid,$data["nodeKey"],$data["selectId"],$data["selectName"]);
                if($res["operateStatus"]=="success"){
                                Db::commit();
                                return json_encode(["msg"=>"","state"=>1]);
                            }else{
                                Db::rollBack();
                                return json_encode(["msg"=>"系统繁忙请稍后再试","state"=>2]);
                            }
            } else {
                Db::rollBack();
                return json_encode(["msg" => "系统繁忙请稍后再试", "state" => 2]);
            }
        } else {
            return json_encode(["msg" => "请正确提交", "state" => 2]);
        }
    }
    //保存申请
    public function baocunapply()
    {
        $request = Request::instance();


        $data = $request->post();
        if ($data) {
            //print_r($data);exit;
            $ckfb=db("system_param")->where(["k"=>'chaiFenRenGuiDang'])->value("v");
            if(!$ckfb){
                $dataup["sfxyfk"]=1;
            }else{
                $dataup["sfxyfk"]=0;
            }
            if ($data["aid"])
                $dataup["id"] = $data["aid"];
            else
                return json_encode(["msg" => "请正确提交", "state" => 2]);
            if ($data["jxs"])
                $dataup["jxs_id"] = $data["jxs"];
            else
                return json_encode(["msg" => "经销商不能为空", "state" => 2]);
            if ($data["title"])
                $dataup["title"] = $data["title"];
            else
                return json_encode(["msg" => "主题不能为空", "state" => 2]);
            $dataup["attach"] = $data["fujian"];
            $dataup["is_notice"] = $data["is_notice"];
            $dataup["status"] = $data["state"];
            $dataup["ptime"] = time();
            $dataup["puser"] = Session::get("employee_id");
            Db::startTrans();
            try {
                $ys=$this->tiys($data["aid"]);
                    if($ys===0&&$data['state']==3)
                        return json_encode(["msg" => "尚未设定ti预算格式无法提交", "state" => 2]);
                $res1 = Db::table("cg_ti")->update($dataup);

                $savetype = $data['state'];
                if ($savetype == '3') {
                    if($ys){
                        Db::table("yusuan_detail")->insertAll($ys);
                    }
                    $flowId = db('cg_workflowset')->where(['id' => '1'])->value('flow_id');

                    $data2 = [];
                    $data2['accessToken'] = session('accessToken');
                    $data2['flowId'] = $flowId;
                    $data2 = $this->curl_post(config('workflow_url').'/horizon/workflow/rest/flow/support/open.wf', $data2);
                    $insert = [];
                    $insert['ywlx'] = 3;
                    $row = db('cg_ti')->where('id', $data["aid"])->field('title,sn')->find();
                    $insert['rwmcjbh'] = $row['title'] . '[' . $row['sn'] . ']';
                    $insert['yw_id'] = $data["aid"];
                    $insert['status'] = 1;
                    $insert['department_id'] = db('department_employee')->where(['index' => 1, 'employee_id' => session('employee_id')])->value('department_id');
                    $insert['sqr_id'] = session('employee_id');
                    $insert['workId'] = $data2->workId;
                    $insert['trackId'] = $data2->flowNode->trackId;
                    db('cg_workflow')->insert($insert);
                }

            } catch (\Exception $e) {
                //echo $e->getMessage();
                Db::rollBack();
                return json_encode(["msg" => "系统繁忙请稍后再试", "state" => 2]);
            }
            if ($res1) {

                Db::commit();

                return json_encode(["msg" => "", "state" => 1]);
            } else {
                Db::rollBack();
                return json_encode(["msg" => "系统繁忙请稍后再试", "state" => 2]);
            }
        } else {
            return json_encode(["msg" => "请正确提交", "state" => 2]);
        }
    }

    public function dataview($did){
        $de=db::table("cg_ti_list")->where(["id"=>$did])->find();
        $de["chanpin"]=Db::table("pro_products")->where(["id"=>$de["product"]])->value("pro_name");
        $de["kemu"]=Db::table("cg_feiyongkemu3")->where(["id"=>$de["feetype"]])->value("title");
        $this->assign("de",$de);
        $net=Db::table("cg_net")->where(["id"=>$de["net_id"]])->find();
        $this->assign("net",$net);
        $apply=Db::table("cg_ti")->where(["id"=>$de["ti_id"]])->find();
        $this->assign("apply",$apply);
        $fb = Db::table("all_ti_feeback_list")->where(["apply_id" => $apply["id"], "type" => 0, "is_deleted" => 0, "is_actived" => 1])->find();
        $this->assign("fb",$fb);
        $system=Db::table("cg_system")->where(["id"=>$net["system_id"]])->find();
        $jxs=Db::table("cg_jxs")->where(["id"=>$system["jxs"]])->find();
        $this->assign("jxs",$jxs);
        $netci=Db::table("cg_net_ci")->where(["net_id"=>$net["id"]])->find();
        $this->assign("netci",$netci);
        $logs=$this->getlog($apply["id"]);
        $this->assign("logs",$logs);
        return $this->fetch();
    }
    public function gostate($aid, $state)
    {
        $data["id"] = $aid;
        $cate_id=db("cg_ti")->where(["id"=>$aid])->value("cate_id");
        $ys=$this->tiys($aid);
        if($ys===0)
            return json_encode(["msg" => "尚未设定ti预算格式无法提交", "state" => 2]);
        $data["status"] = $state;
        $data["ptime"] = time();
        $data["puser"] = Session::get("employee_id");
        Db::startTrans();
        try {

            $res1 = Db::table("cg_ti")->update($data);
            if($ys){
                Db::table("yusuan_detail")->insertAll($ys);
            }
            if($cate_id==1)
                $flowId = db('cg_workflowset')->where(['id' => '1'])->value('flow_id');
            else if($cate_id==2)
                $flowId = db('cg_workflowset')->where(['id' => '21'])->value('flow_id');
            else if($cate_id==3)
                $flowId = db('cg_workflowset')->where(['id' => '22'])->value('flow_id');
            $data = [];
            $data['accessToken'] = session('accessToken');
            $data['flowId'] = $flowId;
            $data = $this->curl_post(config('workflow_url').'/horizon/workflow/rest/flow/support/open.wf', $data);
            $insert = [];
            if($cate_id==1){
                $insert['ywlx'] = 3;
            }else if($cate_id==2){
                $insert['ywlx'] = 21;
            }else{
                 $insert['ywlx'] = 22;
            }
           
            $row = db('cg_ti')->where('id', $aid)->field('title,sn')->find();
            $insert['rwmcjbh'] = $row['title'] . '[' . $row['sn'] . ']';
            $insert['yw_id'] = $aid;
            $insert['status'] = 1;
            $insert['department_id'] = db('department_employee')->where(['index' => 1, 'employee_id' => session('employee_id')])->value('department_id');
            $insert['sqr_id'] = session('employee_id');
            $insert['workId'] = $data->workId;
            $insert['trackId'] = $data->flowNode->trackId;
            db('cg_workflow')->insert($insert);

        } catch (\Exception $e) {
            //echo $e->getMessage();
            Db::rollBack();
            return json_encode(["msg" => $e->getMessage(), "state" => 2]);
        }
        if ($res1) {

            Db::commit();


            return json_encode(["msg" => "", "state" => 1]);
        } else {
            Db::rollBack();
            return json_encode(["msg" => "系统繁忙请稍后再试", "state" => 2]);
        }
    }

    public function shanchuap($aid)
    {

        Db::startTrans();
        try {

             //是否解锁原单
            $yuanid=db("cg_ti")->where(["id" => $aid])->value("old");
            if($yuanid){
                db("cg_ti")->where(["id"=>$yuanid])->update(["is_ydqx"=>0]);
            }
            $res1 = Db::table("cg_ti")->where(["id" => $aid])->delete();
            $res2 = Db::table("cg_ti_list")->where(["ti_id" => $aid])->delete();

             $ys=Db::table("yusuan")->alias("y")->join("yusuan_detail yd","yd.yid=y.id")->where("Y.type=1 and yd.aid=$aid")->field("yd.id")->select();
              if($ys){
                $ysarr=[];
                for($i=0;$i<count($ys);$i++){
                  $ysarr[]=$ys[$i]["id"];
                }
                $ysarr=implode(',',$ysarr);
                db("yusuan_detail")->where("id in($ysarr)")->delete();
              }
             
        } catch (\Exception $e) {
            //echo $e->getMessage();
            Db::rollBack();
            return json_encode(["msg" => "系统繁忙请稍后再试", "state" => 2]);
        }
        if ($res1) {

            Db::commit();


            return json_encode(["msg" => "", "state" => 1]);
        } else {
            Db::rollBack();
            return json_encode(["msg" => "系统繁忙请稍后再试", "state" => 2]);
        }
    }

    public function quxiaoap($aid)
    {
        $data["id"] = $aid;
        $data["is_actived"] = 0;
        $data["modifiled_on"] = date("Y-m-d H:i:s");
        Db::startTrans();
        try {


            $res1 = Db::table("ti_apply")->update($data);


        } catch (\Exception $e) {
            //echo $e->getMessage();
            Db::rollBack();
            return json_encode(["msg" => "系统繁忙请稍后再试", "state" => 2]);
        }
        if ($res1) {

            Db::commit();


            return json_encode(["msg" => "", "state" => 1]);
        } else {
            Db::rollBack();
            return json_encode(["msg" => "系统繁忙请稍后再试", "state" => 2]);
        }
    }

    //取消
    public function quxiao($aid)
    {
        $apply = Db::table("cg_ti")->alias("ap")
            ->join("cg_ti yuan", "ap.old=yuan.id", "LEFT")
            ->join("cg_ti next", "ap.new=next.id", "LEFT")
            ->join("ti_state s", "ap.status=s.id")
            ->join("employee ec", "ap.cuser=ec.id", "LEFT")
            ->join("job_employee je", "ec.id=je.employee_id", "LEFT")
            ->join("job j", "je.job_id=j.id", "LEFT")
            ->join("department_employee de", "ec.id=de.employee_id", "LEFT")
            ->join("department d", "de.department_id=d.id", "LEFT")
            ->join("cg_jxs jx", "ap.jxs_id=jx.id")
            ->join("cg_market_zoning jz", "jx.zoning=jz.id", "LEFT")
            ->join("cg_market_provice jp", "jx.provice=jp.id", "LEFT")
            ->join("cg_market_city jc", "jx.city=jc.id", "LEFT")
            ->where(["ap.id" => $aid, "de.index" => 1])
            ->field("ap.title,ap.sn as no,yuan.sn as yuanno,next.sn as nextno,s.title as zhuangtai,ec.em_name as cname,j.job_name,d.de_name,ap.ctime,jx.title as jingxiao,jz.title as fenqu,jp.title as sheng,jc.title as shi")
            ->find();
        $apply["created_on"] = date("Y-m-d", $apply["ctime"]);
        $this->assign("apply", $apply);

        $applynet = Db::table("ti_apply")->query("select apd.net_id,sum(apd.totalExpectedSales) as sellnums,sum(apd.bucha) as buchas,sum(apd.pizhunweishui) as zonges,sum(apd.pizhunhanshui) as hanshuis,sum(apd.now_price*p.box_num*apd.totalExpectedSales) as xiaoshoues from cg_ti as ap inner join cg_ti_list as apd on apd.ti_id=ap.id inner join pro_products as p on apd.product=p.id where ap.id=$aid group by apd.net_id ");
        //print_r($applynet);
        $this->assign("applynet", $applynet);
        $net_num = count($applynet);
        $this->assign("net_num", $net_num);
        $xiao = 0;
        for ($i = 0; $i < count($applynet); $i++) {
            $xiao += $applynet[$i]["xiaoshoues"];
        }
        $this->assign("xiao", $xiao);
        $applyde = Db::table("cg_ti")->alias("ap")
            ->join("cg_ti_list apd", "apd.ti_id=ap.id")
            ->join("cg_net n", "apd.net_id=n.id", "LEFT")
            ->join("cg_system s", "n.system_id=s.id", "LEFT")
            ->join("pro_products p", "apd.product=p.id")
            ->join("pro_sku sk", "p.sku_id=sk.id")
            ->join("pro_series ps", "sk.series_id=ps.id")
            ->join("pro_price pp", "pp.pid=p.id")
            ->join("cg_feiyongkemu3 f3", "apd.feetype=f3.id")
            ->join("cg_paymethod cp", "apd.paymethod=cp.id")
            ->join("cg_fijiru cf", "apd.project=cf.id")
            ->join("cg_fijiruzd fj", "apd.jrbm=fj.id")->join("department d", "fj.title=d.id")
            ->where(["ap.id" => $aid])->order("apd.net_id,apd.product")
            ->field("ap.sn as no,apd.sn as detail_no,apd.net_id,apd.id as did,apd.is_bu,n.title as net,s.title as xitong,ps.series_name,p.pro_name,apd.start as start_time,apd.end as end_time,apd.expCanTime as hexiao_time,apd.totalExpectedSales as sell_num,apd.bucha,p.unit,p.box_num,pp.factory,apd.yuan_price,apd.now_price,apd.wangdian_price,apd.lingshou_price,apd.huodong_price,f3.title as feiyong3,apd.pizhunweishui as zonge,apd.pizhunhanshui as hanshui,apd.brief as beizhu,apd.head as fuzeren,cp.title as zffs,cf.title as jrfa,(apd.now_price*p.box_num*apd.totalExpectedSales) as xiaoshoue,apd.feiyongmiaoshu as remark,d.de_name,apd.shuilv,apd.isVAT as dikou,apd.zhejia,apd.status as tag")
            ->select();
        // echo Db::table("cg_ti")->getLastsql();
        for ($i = 0; $i < count($applyde); $i++) {
            $applyde[$i]["start_time"] = date("Y-m-d", $applyde[$i]["start_time"]);
            $applyde[$i]["end_time"] = date("Y-m-d", $applyde[$i]["end_time"]);
            $applyde[$i]["hexiao_time"] = date("Y-m-d", $applyde[$i]["hexiao_time"]);
        }
        //print_r($applyde);exit;
        $this->assign("applyde", $applyde);
        $zong = Db::table("cg_ti_list")->where(["ti_id" => $aid])->field("sum(pizhunhanshui) as zongshu")->find();
        $this->assign("zong", $zong);

        $this->assign("aid", $aid);
        return $this->fetch();
    }

    //取消处理
    public function quxiaochuli()
    {
        $request = Request::instance();


        $data = $request->post();

        if ($data) {
            $aid = $data["aid"];
            //print_r($data);exit;
            //获得单据中现存的单子
            $all = Db::table("cg_ti_list")->where(["ti_id" => $data['aid']])->select();
            $jishu = 0;
            $qx = [];
            $did = [];
            for ($i = 0; $i < count($data["did"]); $i++) {
                if (trim($data["quxiaoyuanyin"][$i])) {
                    $qx[] = ["id" => $data["did"][$i], "yuanyin" => $data["quxiaoyuanyin"][$i]];
                    $jishu++;
                    $did[] = $data["did"][$i];
                }
            }
            //print_r($qx);exit;
            if (!$jishu) {
                return json_encode(["msg" => "至少删除一条明细", "state" => 2]);
            }

            Db::startTrans();
            try {
                //原单
                $apply = Db::table("cg_ti")->where(["id" => $aid])->find();

                //生成单号

                $strnum = $this->produceSN();
                $addapply = $apply;
                unset($addapply["id"]);
                $addapply["sn"] = $strnum;
                $addapply["ctime"] = time();
                $addapply["ptime"] = time();
                $addapply["old"] = $aid;
                $addapply["status"] = 1;
                $addapply["attach"] = $data["attach"];
                $addapply["cate_id"] = 3;
                $addapply["cuser"] = Session::get("employee_id");
                $addapply["puser"] = Session::get("employee_id");
                //print_r($addapply);exit;
                $res1 = Db::table("cg_ti")->insertGetId($addapply);
                $removedata = [];
                for ($i = 0; $i < count($all); $i++) {
                    for ($j = 0; $j < count($qx); $j++) {
                        //echo $all[$i]["id"]."---".$qx[$j]["id"]."|";
                        if ($all[$i]["id"] == $qx[$j]["id"]) {
                            $tmp = $all[$i];
                            $tmp["refer_id"] = $tmp["id"];
                            $tmp["cancel_reason"] = $qx[$j]["yuanyin"];
                            $tmp["ctime"] = time();
                            $tmp["ptime"] = time();
                            $tmp["cuser"] = Session::get("employee_id");
                            $tmp["puser"] = Session::get("employee_id");
                            $tmp["ti_id"] = $res1;
                            $tmp["status"] = 2;
                            unset($tmp["id"]);
                            $removedata[] = $tmp;
                            //echo 1;
                        }
                    }
                }
                //print_r($removedata);exit;
                //插入新明细
                $res2 = Db::table("cg_ti_list")->insertAll($removedata);
                 //原明细
                $applymx = Db::table("cg_ti_list")->where(["ti_id" => $aid])->select();
                Db::table("cg_ti")->where(["id" => $aid])->update(["is_ydqx"=>1]);
                $savetype = $data["state"];
                
                if($data["state"]==3){
                    $flowId = db('cg_workflowset')->where(['id' => '22'])->value('flow_id');
                    $datawf = [];
                    $datawf['accessToken'] = session('accessToken');
                    $datawf['flowId'] = $flowId;
                    $datawf = $this->curl_post(config('workflow_url').'/horizon/workflow/rest/flow/support/open.wf', $datawf);
                    $insert = [];
                    $insert['ywlx'] = 22;
                    $row = db('cg_ti')->where('id', $res1)->field('title,sn')->find();
                    $insert['rwmcjbh'] = $row['title'] . '[' . $row['sn'] . ']';
                    $insert['yw_id'] = $res1;
                    $insert['status'] = 1;
                    $insert['department_id'] = db('department_employee')->where(['index' => 1, 'employee_id' => session('employee_id')])->value('department_id');
                    $insert['sqr_id'] = session('employee_id');
                    $insert['workId'] = $datawf->workId;
                    $insert['trackId'] = $datawf->flowNode->trackId;
                    db('cg_workflow')->insert($insert);
                    db('cg_ti')->where('id', $res1)->update(["status"=>3]);
                }
            } catch (\Exception $e) {
                //echo $e->getMessage();
                Db::rollBack();
                return json_encode(["msg" => "系统繁忙请稍后再试", "state" => 2]);
            }
            if ($res1 && $res2) {

                Db::commit();


                return json_encode(["msg" => "", "state" => 1]);
            } else {
                Db::rollBack();
                return json_encode(["msg" => "系统繁忙请稍后再试", "state" => 2]);
            }

        } else {
            return json_encode(["msg" => "请正确提交", "state" => 2]);
        }
    }

    //删除取消草稿
    public function shanchuqx($aid)
    {
        //
        $yuan = Db::table("ti_apply")->where(["id" => $aid])->find();
        $yuanid = $yuan["yuan_id"];
        $yuande = Db::table("ti_apply_detail")->where(["apply_id" => $aid])->field("yuanmingxi")->select();
        $yuandelist = [];

        for ($i = 0; $i < count($yuande); $i++) {
            $yuandelist[] = $yuande[$i]["yuanmingxi"];
        }
        //return json_encode(["msg"=>"系统繁忙请稍后再试","state"=>2]);
        $str = implode(',', $yuandelist);

        try {
            //恢复旧单
            Db::table("ti_apply")->where(["id" => $yuanid])->update(["tag" => 0]);
            $res2 = Db::table("ti_apply")->where(["id" => $aid])->update(["is_deleted" => 1]);
            //恢复旧单明细
            $res1 = Db::table("ti_apply_detail")->where("id in ($str)")->update(["is_actived" => 1]);
        } catch (\Exception $e) {
            //echo $e->getMessage();
            Db::rollBack();
            return json_encode(["msg" => "系统繁忙请稍后再试", "state" => 2]);
        }
        if ($res1 && $res2) {

            Db::commit();


            return json_encode(["msg" => "", "state" => 1]);
        } else {
            Db::rollBack();
            return json_encode(["msg" => "系统繁忙请稍后再试", "state" => 2]);
        }
    }

    //异动
    public function yidong($aid)
    {

        $apply = Db::table("cg_ti")->alias("ap")
            ->join("cg_ti yuan", "ap.old=yuan.id", "LEFT")
            ->join("cg_ti next", "ap.new=next.id", "LEFT")
            ->join("ti_state s", "ap.status=s.id")
            ->join("employee ec", "ap.cuser=ec.id", "LEFT")
            ->join("job_employee je", "ec.id=je.employee_id", "LEFT")
            ->join("job j", "je.job_id=j.id", "LEFT")
            ->join("department_employee de", "ec.id=de.employee_id", "LEFT")
            ->join("department d", "de.department_id=d.id", "LEFT")
            ->join("cg_jxs jx", "ap.jxs_id=jx.id")
            ->join("cg_market_zoning jz", "jx.zoning=jz.id", "LEFT")
            ->join("cg_market_provice jp", "jx.provice=jp.id", "LEFT")
            ->join("cg_market_city jc", "jx.city=jc.id", "LEFT")
            ->where(["ap.id" => $aid, "de.index" => 1])
            ->field("ap.title,ap.sn as no,yuan.sn as yuanno,next.sn as nextno,s.title as zhuangtai,ec.em_name as cname,j.job_name,d.de_name,ap.ctime,jx.title as jingxiao,jz.title as fenqu,jp.title as sheng,jc.title as shi")
            ->find();
        $apply["created_on"] = date("Y-m-d", $apply["ctime"]);
        $this->assign("apply", $apply);


        $applynet = Db::table("cg_ti")->query("select apd.net_id,sum(apd.totalExpectedSales) as sellnums,sum(apd.bucha) as buchas,sum(apd.amount) as zonges,sum(apd.hanshui) as hanshuis,sum(apd.now_price*p.box_num*apd.totalExpectedSales) as xiaoshoues from cg_ti as ap inner join cg_ti_list as apd on apd.ti_id=ap.id inner join pro_products as p on apd.product=p.id where ap.id=$aid group by apd.net_id ");
        $this->assign("applynet", $applynet);
        $net_num = count($applynet);
        $this->assign("net_num", $net_num);
        $xiao = 0;
        for ($i = 0; $i < count($applynet); $i++) {
            $xiao += $applynet[$i]["xiaoshoues"];
        }
        $this->assign("xiao", $xiao);
        $applyde = Db::table("cg_ti")->alias("ap")
            ->join("cg_ti_list apd", "apd.ti_id=ap.id")
            ->join("cg_net n", "apd.net_id=n.id", "LEFT")
            ->join("cg_system s", "n.system_id=s.id", "LEFT")
            ->join("pro_products p", "apd.product=p.id")
            ->join("pro_sku sk", "p.sku_id=sk.id")
            ->join("pro_series ps", "sk.series_id=ps.id")
            ->join("pro_price pp", "pp.pid=p.id")
            ->join("cg_feiyongkemu3 f3", "apd.feetype=f3.id")
            ->join("cg_paymethod cp", "apd.paymethod=cp.id")
            ->join("cg_fijiru cf", "apd.project=cf.id")
            ->join("cg_fijiruzd fj", "apd.jrbm=fj.id")->join("department d", "fj.title=d.id")
            ->where(["ap.id" => $aid])->order("apd.net_id,apd.product")
            ->field("ap.sn as no,apd.sn as detail_no,apd.net_id,apd.id as did,apd.is_bu,n.title as net,s.title as xitong,ps.series_name,p.pro_name,apd.start as start_time,apd.end as end_time,apd.expCanTime as hexiao_time,apd.totalExpectedSales,apd.bucha,p.unit,p.box_num,pp.factory,apd.yuan_price,apd.now_price,apd.wangdian_price,apd.lingshou_price,apd.huodong_price,f3.title as feiyong3,apd.pizhunweishui as pifuzonge,apd.pizhunhanshui as hanshui,apd.feiyongmiaoshu as remark,apd.head as fuzeren,cp.title as zffs,cf.title as jrfa,(apd.now_price*p.box_num*apd.totalExpectedSales) as xiaoshoue,apd.brief as  beizhu,d.de_name,apd.shuilv,apd.isVAT as dikou,apd.zhejia,apd.status as tag,apd.paymethod as zfid")
            ->select();
        for ($i = 0; $i < count($applyde); $i++) {
            $applyde[$i]["start_time"] = date("Y-m-d", $applyde[$i]["start_time"]);
            $applyde[$i]["end_time"] = date("Y-m-d", $applyde[$i]["end_time"]);
            $applyde[$i]["hexiao_time"] = date("Y-m-d", $applyde[$i]["hexiao_time"]);
        }
        $this->assign("applyde", $applyde);

        //费用支付方式
        $fipay = db('cg_paymethod')->field('id,title')->select();
        $this->assign('fipay', $fipay);
        $this->assign("aid", $aid);

        return $this->fetch();
    }

    //异动操作
    public function yidongchuli()
    {
        $request = Request::instance();


        $data = $request->post();

        if ($data) {
            //print_r($data);exit;
            $yd = [];
            $yddid = [];
            $j = 0;
            for ($i = 0; $i < count($data["did"]); $i++) {
                if (trim($data["yidongyuanyin"][$i])) {
                    $yd[$j]["did"] = $data["did"][$i];
                    $yd[$j]["zonge"] = $data["zonge"][$i];
                    if ($data["bucha"][$i]) {
                        $yd[$j]["bucha"] = $data["bucha"][$i];
                    } else {
                        $yd[$j]["bucha"] = null;
                    }
                    $yd[$j]["dikou"] = $data["dikou"][$i];
                    $yd[$j]["shuilv"] = $data["shuilv"][$i];
                    $yd[$j]["zfid"] = $data["zfid"][$i];
                    $yd[$j]["start_time"] = $data["start_time"][$i];
                    $yd[$j]["end_time"] = $data["end_time"][$i];
                    $yd[$j]["hexiao_time"] = $data["hexiao_time"][$i];
                    $yd[$j]["yidongyuanyin"] = $data["yidongyuanyin"][$i];
                    $yddid[$j] = $data["did"][$i];
                    $j++;
                }
            }
            //print_r($yd);exit;
            if (!$yd) {
                return json_encode(["msg" => "至少一条明细发生异动", "state" => 2]);
            }
            $aid = $data["aid"];
            Db::startTrans();
            try {
                //原单
                $apply = Db::table("cg_ti")->where(["id" => $aid])->find();

                //生成单号

                $strnum = $this->produceSN();
                $addapply = $apply;
                unset($addapply["id"]);
                $addapply["sn"] = $strnum;
                $addapply["ctime"] = time();
                $addapply["ptime"] = time();
                $addapply["old"] = $aid;
                $addapply["status"] = 1;
                $addapply["attach"] = $data["attach"];
                $addapply["cate_id"] = 2;
                $addapply["cuser"] = Session::get("employee_id");
                $addapply["puser"] = Session::get("employee_id");

                //print_r($addapply);exit;
                $res1 = Db::table("cg_ti")->insertGetId($addapply);
                //echo $res1;exit;
                //原明细
                $applymx = Db::table("cg_ti_list")->where(["ti_id" => $aid])->select();
                Db::table("cg_ti")->where(["id" => $aid])->update(["is_ydqx"=>1]);
                //生成新明细
                $datayd = [];
                for ($i = 0; $i < count($applymx); $i++) {
                    if (in_array($applymx[$i]["id"], $yddid)) {
                        //异动
                        $tmp = $applymx[$i];
                        for ($j = 0; $j < count($yd); $j++) {
                            if ($yd[$j]["did"] == $tmp["id"]) {

                                //异动修改
                                //
                                //计算折算率  zong=qian*bucha*zhejia/100
                                if ($tmp["bucha"]) {

                                    $xiangqian = $tmp["pizhunweishui"] * 100 / $tmp["zhejia"] / $tmp["bucha"];

                                    $tmp["zhejia"] = $yd[$j]["zonge"] / $yd[$j]["bucha"] * 100 / $xiangqian;
                                } else {
                                    $tmp["zhejia"] = null;
                                }

                                $tmp["amount"] = $yd[$j]["zonge"];
                                $tmp["bucha"] = $yd[$j]["bucha"];
                                $tmp["isVAT"] = $yd[$j]["dikou"];
                                $tmp["shuilv"] = $yd[$j]["shuilv"];
                                $tmp["hanshui"] = $yd[$j]["zonge"] + $yd[$j]["zonge"] * $yd[$j]["shuilv"] / 100;
                                $tmp["paymethod"] = $yd[$j]["zfid"];
                                $tmp["start"] = strtotime($yd[$j]["start_time"]);
                                $tmp["end"] = strtotime($yd[$j]["end_time"]);
                                $tmp["expCanTime"] = strtotime($yd[$j]["hexiao_time"]);
                                $tmp["ydreason"] = $yd[$j]["yidongyuanyin"];
                                $tmp["status"] = 1;
                                $tmp["pizhunweishui"] = $yd[$j]["zonge"];
                                $tmp["pizhunhanshui"] = $yd[$j]["zonge"] + $yd[$j]["zonge"] * $yd[$j]["shuilv"] / 100;
                                if($yd[$j]["dikou"]){
                                    $tmp["yjsjtrfy"]=$tmp["pizhunweishui"] ;
                                }else{
                                    $tmp["yjsjtrfy"]= $tmp["pizhunhanshui"];
                                }
                                //预计费用率
                                $tmp["yujifeiyonglv"]=$tmp["yjsjtrfy"]/$tmp["totalExpectedSales"]*100;
                                //预计roi
                                //$yujirois=($boxnum*$prolist[$j]["now_price"]* $data["boxunit"][$j]-$basee)*$prolist[$j]["pbmaoli"]/100;
                                $profit=db("pro_products pp")->join("pro_sku sk","pp.sku_id=sk.id")
                                ->join("pro_series ps","sk.series_id=ps.id")->join("pro_category pc","ps.category_id=pc.id")
                                ->join("pro_brands pb","pc.brand_id=pb.id")->where(["pp.id"=>$tmp["product"]])->value("pb.profit");
                                $tmp["yujiroi"]=($tmp["totalExpectedSales"]-$tmp["totalBenchmarkSales"])*$profit/100/$tmp["yjsjtrfy"];
                            }
                        }
                        $tmp["refer_id"] = $tmp["id"];
                        unset($tmp["id"]);
                        $datayd[$i] = $tmp;

                    } else {
                        $tmp = $applymx[$i];
                        $tmp["refer_id"] = $tmp["id"];
                        $tmp["status"] = 0;
                        $tmp["ydreason"] = null;
                        unset($tmp["id"]);
                        $datayd[$i] = $tmp;
                    }
                    $datayd[$i]["ti_id"] = $res1;
                }
                //print_r($datayd);exit;
                $res2 = Db::table("cg_ti_list")->insertAll($datayd);

                    $ys=$this->tiys($res1);
                    if($ys===0&&$data["state"]==3)
                        return json_encode(["msg" => "尚未设定ti预算格式无法提交", "state" => 2]);
                    //$res1 = Db::table("cg_ti")->update($dataup);

                    $savetype = $data["state"];
                    if ($savetype == '3') {
                        if($ys){
                            Db::table("yusuan_detail")->insertAll($ys);
                        }
                        
                    }
                if($data["state"]==3){
                    $flowId = db('cg_workflowset')->where(['id' => '21'])->value('flow_id');
                    $datawf = [];
                    $datawf['accessToken'] = session('accessToken');
                    $datawf['flowId'] = $flowId;
                    $datawf = $this->curl_post(config('workflow_url').'/horizon/workflow/rest/flow/support/open.wf', $datawf);
                    $insert = [];
                    $insert['ywlx'] = 21;
                    $row = db('cg_ti')->where('id', $res1)->field('title,sn')->find();
                    $insert['rwmcjbh'] = $row['title'] . '[' . $row['sn'] . ']';
                    $insert['yw_id'] = $res1;
                    $insert['status'] = 1;
                    $insert['department_id'] = db('department_employee')->where(['index' => 1, 'employee_id' => session('employee_id')])->value('department_id');
                    $insert['sqr_id'] = session('employee_id');
                    $insert['workId'] = $datawf->workId;
                    $insert['trackId'] = $datawf->flowNode->trackId;
                    db('cg_workflow')->insert($insert);
                    db('cg_ti')->where('id', $res1)->update(["status"=>3]);
                }
            } catch (\Exception $e) {

                Db::rollBack();//echo $e->getMessage();exit;
                return json_encode(["msg" =>$e->getMessage(), "state" => 2]);
            }
            if ($res1 && $res2) {

                Db::commit();


                return json_encode(["msg" => "", "state" => 1]);
            } else {
                Db::rollBack();
                return json_encode(["msg" => "系统繁忙请稍后再试", "state" => 2]);
            }

            //print_r($datayd);exit;
        } else {
            return json_encode(["msg" => "请正确提交", "state" => 2]);
        }
    }

    //网点反馈
    public function wangdianfankui($aid)
    {
        $apply = Db::table("cg_ti")->alias("ap")
            ->join("cg_ti yuan", "ap.old=yuan.id", "LEFT")
            ->join("cg_ti next", "ap.new=next.id", "LEFT")
            ->join("ti_state s", "ap.status=s.id")
            ->join("employee ec", "ap.cuser=ec.id", "LEFT")
            ->join("job_employee je", "ec.id=je.employee_id", "LEFT")
            ->join("job j", "je.job_id=j.id", "LEFT")
            ->join("department_employee de", "ec.id=de.employee_id", "LEFT")
            ->join("department d", "de.department_id=d.id", "LEFT")
            ->join("cg_jxs jx", "ap.jxs_id=jx.id")
            ->join("cg_market_zoning jz", "jx.zoning=jz.id", "LEFT")
            ->join("cg_market_provice jp", "jx.provice=jp.id", "LEFT")
            ->join("cg_market_city jc", "jx.city=jc.id", "LEFT")
            ->where(["ap.id" => $aid, "de.index" => 1])
            ->field("ap.title,ap.sn as no,yuan.sn as yuanno,next.sn as nextno,s.title as zhuangtai,ec.em_name as cname,j.job_name,d.de_name,ap.ctime,jx.title as jingxiao,jz.title as fenqu,jp.title as sheng,jc.title as shi,ap.fb as is_fankui")
            ->find();
        $apply["created_on"] = date("Y-m-d", $apply["ctime"]);
        $this->assign("apply", $apply);
        $this->assign("aid", $aid);
        $em = Db::table("employee")->where(["id" => Session::get("employee_id")])->find();
        $this->assign("em", $em);
        $apde = Db::table("cg_ti_list")->query("select apd.net_id,apd.product as pro_id,p.pro_name,n.title as net_name,n.sn as net_no,p.pro_no,sum(apd.boxnum) as sellnums,sum(apd.pizhunweishui) as yuji,sum(apd.totalExpectedSales) as xiaoshoue from cg_ti_list as apd inner join pro_products as p on apd.product=p.id inner join cg_net as n on apd.net_id=n.id where apd.ti_id=$aid group by apd.net_id,apd.product");
        for ($i = 0; $i < count($apde); $i++) {
            $apde[$i]["sellnums"] = round($apde[$i]["sellnums"], 2);
            $apde[$i]["yuji"] = round($apde[$i]["yuji"], 2);
            $apde[$i]["xiaoshoue"] = round($apde[$i]["xiaoshoue"], 2);
        }
        $this->assign("apde", $apde);
        return $this->fetch();
    }

    //整单反馈
    public function allfankui($aid)
    {

        $apply = Db::table("cg_ti")->alias("ap")
            ->join("cg_ti yuan", "ap.old=yuan.id", "LEFT")
            ->join("cg_ti next", "ap.new=next.id", "LEFT")
            ->join("ti_state s", "ap.status=s.id")
            ->join("employee ec", "ap.cuser=ec.id", "LEFT")
            ->join("job_employee je", "ec.id=je.employee_id", "LEFT")
            ->join("job j", "je.job_id=j.id", "LEFT")
            ->join("department_employee de", "ec.id=de.employee_id", "LEFT")
            ->join("department d", "de.department_id=d.id", "LEFT")
            ->join("cg_jxs jx", "ap.jxs_id=jx.id")
            ->join("cg_market_zoning jz", "jx.zoning=jz.id", "LEFT")
            ->join("cg_market_provice jp", "jx.provice=jp.id", "LEFT")
            ->join("cg_market_city jc", "jx.city=jc.id", "LEFT")
            ->where(["ap.id" => $aid, "de.index" => 1])
            ->field("ap.title,ap.sn as no,yuan.sn as yuanno,next.sn as nextno,s.title as zhuangtai,ec.em_name as cname,j.job_name,d.de_name,ap.ctime,jx.title as jingxiao,jz.title as fenqu,jp.title as sheng,jc.title as shi,ap.fb as is_fankui")
            ->find();
        $apply["created_on"] = date("Y-m-d", $apply["ctime"]);
        $this->assign("apply", $apply);
        $em = Db::table("employee")->where(["id" => Session::get("employee_id")])->find();
        $this->assign("em", $em);
        $applyde = Db::table("cg_ti_list")->query("select sum(boxnum) as nums,sum(fb_boxnum) as fans from cg_ti_list where ti_id=$aid");
        $apde["nums"] = round($applyde[0]["nums"], 2);

        if ($apply["is_fankui"]) {
            $apde["fans"] = round($applyde[0]["fans"], 2);

        } else {
            $apde["fans"] = $apde["nums"];

        }
        $this->assign("apde", $apde);

        $aplist = Db::table("cg_ti_list")->query("select d1.feetype as feiyong_id,sum(d1.pizhunhanshui) as hanshui,sum(d1.pizhunweishui) as weishui,sum(d1.fb_shijiweishui) as shijijin,f3.title as kemu3,(select count(DISTINCT net_id) from cg_ti_list as d2 where d2.ti_id=$aid and d2.feetype=d1.feetype )as net_num,(select count(DISTINCT d3.product) from cg_ti_list as d3 where d3.ti_id=$aid and d3.feetype=d1.feetype) as pro_num from cg_ti_list as d1 inner join cg_feiyongkemu3 as f3 on d1.feetype=f3.id where d1.ti_id=$aid group by d1.feetype");
        for ($i = 0; $i < count($aplist); $i++) {
            $aplist[$i]["net_num"] = round($aplist[$i]["net_num"], 2);
            $aplist[$i]["pro_num"] = round($aplist[$i]["pro_num"], 2);
            $aplist[$i]["hanshui"] = round($aplist[$i]["hanshui"], 2);
            if ($apply["is_fankui"]) {
                $aplist[$i]["shijijin"] = round($aplist[$i]["shijijin"], 2);
            } else {
                $aplist[$i]["shijijin"] = $aplist[$i]["weishui"];
            }
        }
        $this->assign("aplist", $aplist);
        $this->assign("aid", $aid);
        //print_r($aplist);exit;
        return $this->fetch();
    }

    //整单反馈操作
    public function alldanfankui()
    {
        $request = Request::instance();


        $data = $request->post();

        if ($data) {
            //print_r($data);exit;
            $aid = $data["aid"];

            $strnum = $this->producefbSN();
            $datalist = ["no" => $strnum, "type" => 0, "apply_id" => $aid, "c_user_id" => Session::get("employee_id"), "created_on" => date("Y-m-d H:i:s"), "state" => 1,
                "remark" => $data["remark"], "fujian" => $data["attach"]
            ];
            //print_r($data);exit;
            //获取原单库存
            $applyde = Db::table("cg_ti_list")->query("select sum(boxnum) as nums from cg_ti_list where ti_id=$aid");
            $yuannum = $applyde[0]["nums"];
            $bili = $data["box_num"] / $yuannum;

            $aplist = Db::table("cg_ti_list")->query("select d1.feetype as feiyong_id,sum(d1.pizhunweishui) as hanshui from cg_ti_list as d1  where d1.ti_id=$aid group by d1.feetype");
            // print_r($data);exit;
            $fbi = Db::table("all_ti_feeback_list")->where(["apply_id" => $aid, "is_deleted" => 0, "state" => 7])->count();
            if ($fbi)
                return json_encode(["msg" => "本申请存在已通过的反馈申请，不能使用整单反馈", "state" => 2]);
            Db::startTrans();
            try {
                Db::table("all_ti_feeback_list")->where(["apply_id" => $aid])->update(["is_deleted" => 1]);
                $res2 = Db::table("all_ti_feeback_list")->insertGetId($datalist);

                //所有实际销量按比例增加
                $res = Db::table("ti_apply_detail")->query("update cg_ti_list set fb_shijixiaoliang=totalExpectedSales*$bili,fb_boxnum=boxnum*$bili where ti_id=$aid");

                //安费用纬度处理
                for ($i = 0; $i < count($data["feiyong_id"]); $i++) {
                    for ($j = 0; $j < count($aplist); $j++) {
                        if ($data["feiyong_id"][$i] == $aplist[$j]["feiyong_id"]) {
                            //计算比例
                            $bilishui = $data["fankuijine"][$i] / $aplist[$j]["hanshui"];
                            if (trim($data["shuilv"][$i]))
                                $shuilv = $data["shuilv"][$i];
                            else
                                $shuilv = 0;

                            $nowt = time();
                            $user = Session::get("employee_id");
                            //return json_encode(["msg"=>"update ti_apply_detail set fankuishuilv={$shuilv},fankuidikou={$data["is_di"][$i]},fankuijine=(pifzonge+pifuzonge*shuilv/100)*$bilishui/(1+{$shuilv}/100) where is_deleted=0 and apply_id=$aid and feiyong_id={$data["feiyong_id"][$i]}","state"=>2]);
                            //$is_di=
                            //a=b/(1+shui/100)
                            if($data["is_di"][$i]==1){
                                $res = Db::table("ti_apply_detail")->query("update cg_ti_list set fb_shuilv={$shuilv},fb_isVAT={$data["is_di"][$i]},fb_brief='{$data["remark"]}',fb_shijiweishui=(pizhunweishui*$bilishui),fb_time=$nowt,fb_hanshui=(pizhunweishui*$bilishui)*(1+{$shuilv}/100),fb_user=$user,hx_status=5,fb_shijitourufeiyong=(pizhunweishui*$bilishui) where ti_id=$aid and feetype={$data["feiyong_id"][$i]}");
                            }else{
                                $res = Db::table("ti_apply_detail")->query("update cg_ti_list set fb_shuilv={$shuilv},fb_isVAT={$data["is_di"][$i]},fb_brief='{$data["remark"]}',fb_shijiweishui=(pizhunweishui*$bilishui),fb_time=$nowt,fb_hanshui=(pizhunweishui*$bilishui)*(1+{$shuilv}/100),fb_user=$user,hx_status=5,fb_shijitourufeiyong=(pizhunweishui*$bilishui)*(1+{$shuilv}/100) where ti_id=$aid and feetype={$data["feiyong_id"][$i]}");
                            }
                            


                        }
                    }
                }
                //return;
                $dataup = ["id" => $aid, "fb" => 1, "fd_id" => $res2];
                Db::table("cg_ti")->update($dataup);
            } catch (\Exception $e) {
                //echo $e->getMessage();
                Db::rollBack();
                return json_encode(["msg" => $e->getMessage(), "state" => 2]);
            }

            if ($res2) {
                if($data["state"]==3){
                     $jieguo=$this->gowork(17,$res2);
                    if($jieguo==json_encode(['state'=>1,'msg'=>'提交成功'])){
                        Db::commit();
                        return $jieguo;
                    }else{
                        Db::rollBack();
                        return json_encode(["msg"=>"系统繁忙请稍后再试","state"=>2]);
                    }
                }else{
                     Db::commit();
                    return json_encode(["msg" => "", "state" => 1]);
                }
               


            } else {
                Db::rollBack();
                return json_encode(["msg" => "系统繁忙请稍后再试", "state" => 2]);
            }
            //Db::commit();
        } else {
            return json_encode(["msg" => "请正确提交", "state" => 2]);
        }
    }

    //网点反馈处理
    public function wangdianfan()
    {
        $request = Request::instance();


        $data = $request->post();

        if ($data) {
            $aid = $data["aid"];

            //print_r($data);exit;
            $strnum = $this->producefbSN();
            $datalist = ["no" => $strnum, "type" => 0, "apply_id" => $aid, "c_user_id" => Session::get("employee_id"), "created_on" => date("Y-m-d H:i:s"), "state" => 1,
                "remark" => $data["remark"], "fujian" => $data["attach"]
            ];

            $apde = Db::table("cg_ti_list")->query("select apd.net_id,apd.product as pro_id,p.pro_name,n.title as net_name,n.sn as net_no,p.pro_no,sum(apd.boxnum) as sellnums,sum(apd.pizhunweishui) as yuji,sum(apd.totalExpectedSales) as xiaoshoue from cg_ti_list as apd inner join pro_products as p on apd.product=p.id inner join cg_net as n on apd.net_id=n.id where apd.ti_id=$aid group by apd.net_id,apd.product");
            $fbi = Db::table("all_ti_feeback_list")->where(["apply_id" => $aid, "is_deleted" => 0, "state" => 7])->count();
            if ($fbi)
                return json_encode(["msg" => "本申请存在已通过的反馈申请，不能使用网点反馈", "state" => 2]);
            Db::startTrans();
            //print_r($data);exit;
            try {
                Db::table("all_ti_feeback_list")->where(["apply_id" => $aid])->update(["is_deleted" => 1]);
                $res2 = Db::table("all_ti_feeback_list")->insertGetId($datalist);

                for ($i = 0; $i < count($data["nid"]); $i++) {
                    for ($j = 0; $j < count($apde); $j++) {

                        if ($data["nid"][$i] == $apde[$j]["net_id"] && $data["pid"][$i] == $apde[$j]["pro_id"]) {

                            if (trim($data["shuilv"][$i]))
                                $shuilv = $data["shuilv"][$i];
                            else
                                $shuilv = 0;

                            //核算数量比例
                            $box_bi = $data["box_num"][$i] / $apde[$j]["sellnums"];
                            //核算金额比例
                            $jinebili = $data["hexiaojine"][$i] / $apde[$j]["yuji"];
                            $nowt = time();
                            $user = Session::get("employee_id");

                            //$is_di=
                            if($data["is_di"][$i]){
                                $res = Db::table("cg_ti_list")->query("update cg_ti_list set hx_status=0,fb_shuilv={$shuilv},fb_isVAT={$data["is_di"][$i]},fb_shijixiaoliang=totalExpectedSales*{$box_bi},fb_boxnum=boxnum*{$box_bi},fb_brief='{$data["remark"]}',fb_shijiweishui=pizhunweishui*$jinebili,fb_hanshui=((pizhunweishui*$jinebili)+(pizhunweishui*$jinebili)*{$shuilv}/100),fb_shijitourufeiyong=pizhunweishui*$jinebili,fb_time=$nowt,fb_user=$user,hx_status=5 where ti_id=$aid and net_id={$data["nid"][$i]} and product={$data["pid"][$i]}");
                            }else{
                                $res = Db::table("cg_ti_list")->query("update cg_ti_list set hx_status=0,fb_shuilv={$shuilv},fb_isVAT={$data["is_di"][$i]},fb_shijixiaoliang=totalExpectedSales*{$box_bi},fb_boxnum=boxnum*{$box_bi},fb_brief='{$data["remark"]}',fb_shijiweishui=pizhunweishui*$jinebili,fb_hanshui=((pizhunweishui*$jinebili)+(pizhunweishui*$jinebili)*{$shuilv}/100),fb_shijitourufeiyong=((pizhunweishui*$jinebili)+(pizhunweishui*$jinebili)*{$shuilv}/100),fb_time=$nowt,fb_user=$user,hx_status=5 where ti_id=$aid and net_id={$data["nid"][$i]} and product={$data["pid"][$i]}");
                            }
                            

                        }
                    }
                }
                $dataup = ["id" => $aid, "fb" => 1, "fd_id" => $res2];
                Db::table("cg_ti")->update($dataup);
            } catch (\Exception $e) {
                //echo $e->getMessage();
                Db::rollBack();
                return json_encode(["msg" => "系统繁忙请稍后再试", "state" => 2]);
            }

            if ($res2) {
                if($data["state"]==3){
                     $jieguo=$this->gowork(17,$res2);
                    if($jieguo==json_encode(['state'=>1,'msg'=>'提交成功'])){
                        Db::commit();
                        return $jieguo;
                    }else{
                        Db::rollBack();
                        return json_encode(["msg"=>"系统繁忙请稍后再试","state"=>2]);
                    }
                }else{
                     Db::commit();
                    return json_encode(["msg" => "", "state" => 1]);
                }


            } else {
                Db::rollBack();
                return json_encode(["msg" => "系统繁忙请稍后再试", "state" => 2]);
            }

        } else {
            return json_encode(["msg" => "请正确提交", "state" => 2]);
        }
    }

    //核销
    public function hexiao($aid, $type = 0)
    {
        $apply = Db::table("cg_ti")->alias("ap")
            ->join("cg_jxs jx", "ap.jxs_id=jx.id")
            ->join("employee ec", "ap.cuser=ec.id", "LEFT")
            ->where(["ap.id" => $aid])->field("jx.title as jxs,jx.sn,ec.em_name as cname")->find();

        $this->assign("apply", $apply);
        $where = "ap.id=$aid  ";
        switch ($type) {
            case 0:
                #可核销
                $where .= "and apd.hx_status=0 and (apd.hx_wsq is null or apd.hx_wsq>0)";
                break;
            case 2:
                #不予核销
                $where .= "and apd.hx_status=2";
                break;
            case 1:
                #核销中
                $where .= "and apd.hx_status=1";
                break;
            case 3:
                #未反馈
                $where .= "and apd.hx_status=3";
                break;
            case 4:
                #未反馈
                $where .= "and apd.hx_status=4";
                break;
            case 5:
                #未反馈
                $where .= "and apd.is_lock=1";
                break;
            case 6:
                $where .= "and apd.hx_status=5";
                break;
            default:
                # code...
                break;
        }

        $ade = Db::table("cg_ti_list")->alias("apd")
            ->join("cg_ti ap", "apd.ti_id=ap.id")
            ->join("employee ec", "ap.cuser=ec.id", "LEFT")
            ->join("cg_net n", "apd.net_id=n.id", "LEFT")
            ->join("cg_system s", "n.system_id=s.id", "LEFT")
            ->join("pro_products p", "apd.product=p.id","LEFT")
            ->join("pro_sku sk", "p.sku_id=sk.id","LEFT")
            ->join("pro_series ps", "sk.series_id=ps.id","LEFT")
            ->join("pro_category pc", "ps.category_id=pc.id","LEFT")
            ->join("pro_brands pb", "pc.brand_id=pb.id","LEFT")
            ->join("cg_feiyongkemu3 f3", "apd.feetype=f3.id","LEFT")
            ->where($where)->order("apd.id")
            ->field("apd.id,ap.sn as no,apd.sn as detail_no,ec.em_name as cname,n.title as net_name,s.title as sys_name,pb.brand_name,f3.title as kemu3,apd.fb_shijiweishui as fankuijine,apd.fb_hanshui as fankuihanshui,apd.hx_yihexiao,apd.hx_sqz,apd.paymethod as zfid,apd.start as start_time,apd.fb_shuilv as fankuishuilv,ap.id as apid,apd.fb_shijitourufeiyong,apd.fb_isVAT")
            ->select();
        for ($i = 0; $i < count($ade); $i++) {
            $ade[$i]["hexiao"] = $ade[$i]["hx_yihexiao"] + $ade[$i]["hx_sqz"];
            $ade[$i]["weihe"] = $ade[$i]["fankuijine"] - $ade[$i]["hexiao"];
            $ade[$i]["weiheh"]=$ade[$i]["weihe"]*(1+$ade[$i]["fankuishuilv"]/100);
            if($ade[$i]["fb_isVAT"])
                $ade[$i]["weihes"]=$ade[$i]["weihe"];
            else
                $ade[$i]["weihes"]=$ade[$i]["weiheh"];
            $ade[$i]["start_time"] = date("Y-m-d", $ade[$i]["start_time"]);

            $ade[$i]["sj"]=$ade[$i]["weiheh"]-$ade[$i]["weihe"];
        }
        // print_r($ade);exit;
        $fipay = db('cg_paymethod')->field('id,title')->select();
        $this->assign('fipay', $fipay);
        $this->assign("ade", $ade);
        $this->assign("aid", $aid);
        $this->assign("type", $type);
        return $this->fetch();
    }

    //更换经销商
    public function genhuanjingxiao()
    {
        $request = Request::instance();


        $data = $request->post();
        DB::table("ti_apply")->query("select * from ti_apply as ap inner join ti_apply_detail as apd on ap.id=apd.apply_id");


        return $this->fetch();
    }

    //设置发票信息
    public function setfapiao()
    {
        //费用支付方式
        $fipay = db('cg_paymethod')->field('id,title')->select();
        $this->assign('fipay', $fipay);

        return $this->fetch();
    }

    //获取单挑明细信息
    public function dantiaomingxi($did)
    {
        $res = Db::table("cg_ti_list")->where(["id" => $did])
            ->field("(fb_shijitourufeiyong) as fankuijine,hx_sqz,hx_yihexiao")->find();
        if ($res["hx_sqz"])
            $sq = $res["hx_sqz"];
        else
            $sq = 0;
        if ($res["hx_yihexiao"])
            $yh = $res["hx_yihexiao"];
        else
            $yh = 0;
        $res["hexiao"] = $sq + $yh;
        $res["weihe"] = $res["fankuijine"] - $res["hexiao"];
        return json_encode($res);

    }

    //不予核销
    public function nohexiao($did, $state)
    {
        Db::startTrans();
        try {
            Db::table("cg_ti_list")->where(["id" => $did])->update(["hx_status" => 2]);
            // echo Db::table("cg_ti_list")->getLastsql();exit;
        } catch (\Exception $e) {
            //echo $e->getMessage();
            Db::rollBack();
            return json_encode(["msg" => "系统繁忙请稍后再试", "state" => 2]);
        }
        Db::commit();
        return json_encode(["msg" => "", "state" => 1]);

    }

    //核销预览
    public function hexiaoscan()
    {
        $request = Request::instance();


        $data = $request->post();
        $this->assign("zongbeizhu", $data["zongbeizhu"]);
        //print_r($data);
        //处理接收数据
        $postdata = [];
        for ($i = 0; $i < count($data["dids"]); $i++) {
            $postdata[$i] = ["did" => $data["dids"][$i], "isfa" => $data["isfa"][$i],
                "fapiao" => $data["fapiao"][$i], "shuilv" => $data["shuilv"][$i], "isdi" => $data["isdi"][$i],
                "weishui" => $data["weishui"][$i], "shuijin" => $data["shuilv"][$i] * $data["weishui"][$i] / 100,
                "hanshui" => $data["shuilv"][$i] * $data["weishui"][$i] / 100 + $data["weishui"][$i], "beizhu" => $data["beizhu"][$i], "zfid" => $data["zfid"][$i]
            ];
        }
        $this->assign("postdata", $postdata);
        $eid = Session::get("employee_id");
        $aid = $data["aid"];
        $user = Db::table("employee")->alias("e")
            ->join("job_employee je", "e.id=je.employee_id", "LEFT")
            ->join("job j", "je.job_id=j.id", "LEFT")
            ->join("department_employee de", "e.id=de.employee_id", "LEFT")
            ->join("department d", "de.department_id=d.id", "LEFT")
            ->where(["e.id" => $eid, "de.index" => 1, "d.is_actived" => 1, "d.is_deleted" => 0, "j.is_actived" => 1, "j.is_deleted" => 0])
            ->field("e.id,e.em_name,d.de_name,j.job_name")
            ->find();
        $this->assign("user", $user);
        $time = date("Y-m-d H:i");
        $this->assign("time", $time);
        $apply = Db::table("cg_ti")->alias("ap")
            ->join("cg_jxs jx", "ap.jxs_id=jx.id")
            ->join("employee ec", "ap.cuser=ec.id", "LEFT")
            ->where(["ap.id" => $aid])->field("jx.title as jxs,jx.sn,ec.em_name as cname,jx.id as jxs_id")->find();

        $this->assign("apply", $apply);

        $dids = implode(',', $data["dids"]);

        $ade = Db::table("cg_ti_list")->alias("apd")
            ->join("cg_ti ap", "apd.ti_id=ap.id")
            ->join("employee ec", "ap.cuser=ec.id", "LEFT")
            ->join("cg_net n", "apd.net_id=n.id", "LEFT")
            ->join("cg_system s", "n.system_id=s.id", "LEFT")
            ->join("pro_products p", "apd.product=p.id", "LEFT")
            ->join("pro_sku sk", "p.sku_id=sk.id", "LEFT")
            ->join("pro_series ps", "sk.series_id=ps.id", "LEFT")
            ->join("pro_category pc", "ps.category_id=pc.id", "LEFT")
            ->join("pro_brands pb", "pc.brand_id=pb.id", "LEFT")
            ->join("cg_feiyongkemu3 f3", "apd.feetype=f3.id")
            ->where("ap.id=$aid and apd.id in($dids)")
            ->field("apd.id,ap.sn as no,apd.sn as detail_no,ec.em_name as cname,n.title as net_name,s.title as sys_name,pb.brand_name,f3.title as kemu3,apd.fb_shijiweishui as fankuijine,apd.fb_hanshui as fankuihanshui,apd.hx_yihexiao,apd.hx_sqz,apd.paymethod as zfid,apd.start as start_time,apd.fb_shuilv as fankuishuilv,ap.id as apid,apd.fb_shijitourufeiyong,apd.fb_isVAT")
            ->select();
        for ($i = 0; $i < count($ade); $i++) {
            $ade[$i]["hexiao"] = $ade[$i]["hx_yihexiao"] + $ade[$i]["hx_sqz"];
            $ade[$i]["weihe"] = $ade[$i]["fankuijine"] - $ade[$i]["hexiao"];
            $ade[$i]["start_time"] = date("Y-m-d", $ade[$i]["start_time"]);
        }
        // print_r($ade);exit;
        $fipay = db('cg_paymethod')->field('id,title')->select();
        $this->assign('fipay', $fipay);
        $this->assign("ade", $ade);
        $this->assign("aid", $aid);
        $datastr = json_encode($data);
        $this->assign("datastr", $datastr);
        //print_r($data);
        return $this->fetch();
    }

    //生成反馈sn
    public function producehxSN()
    {
        //生成编号
        $max = db('cg_ti_hexiao')->where('sn', 'like', date('Ymd') . '%')->max('sn'); //编号递增开始位置基础

        if ($max) {
            $max = (double)$max;
            $insert_sn = $max + 1;
        } else {
            $insert_sn = date('Ymd') . '0001';
        }
        return $insert_sn;
    }

    //核销提交处理
    public function hexiaochuli()
    {
        $request = Request::instance();
        $data = $request->post();
        $formdata = json_decode($data["form-data"], true);

        // print_r($formdata["isdi"]);exit;
        $aid = $formdata["aid"];
        $apply = Db::table("cg_ti")->where("id=$aid")->find();
        $buhelist = [];
        if (isset($formdata["yuebuhe"])) {
            $buhelist = $formdata["yuebuhe"];
        }
        Db::startTrans();
        try {
            //生成核销主表数据

            $strnum = $this->producehxSN();
            if (isset($data["isgui"]))
                $isgui = 1;
            else
                $isgui = 0;
            $notax = 0;
            $hastax = 0;
            $shuijinheji = 0;
            $tax=0;
            for ($i = 0; $i < count($formdata["dids"]); $i++) {
                $notax += $formdata["weishui"][$i];
                $shuijinheji += ($formdata["weishui"][$i] * $formdata["shuilv"][$i] / 100);
               if($formdata["isdi"][$i])
                    $tax+=$formdata["weishui"][$i];
                else
                    $tax+=($formdata["weishui"][$i]+($formdata["weishui"][$i] * $formdata["shuilv"][$i] / 100));
            }
             $hastax= ($notax + $shuijinheji);
            $he_app_data = [
                "sn" => $strnum, "cuser" => Session::get("employee_id"), "ctime" => time(), "puser" => Session::get("employee_id"), "ptime" => time(), "status" => 1, "attach" => $data["attach"], "beizhu" => $data["remark"], "jxs_id" => $apply["jxs_id"], "yzfje" => 0, "tax" => $tax, "notax" => $notax,"hastax"=>$hastax, "shuijinheji" => $shuijinheji,
                "guidangtixing" => $isgui
            ];
            //print_r($he_app_data);exit;
            $res1 = Db::table("cg_ti_hexiao")->insertGetId($he_app_data);
            //插入明细
            $detail = [];
            for ($i = 0; $i < count($formdata["dids"]); $i++) {
                $thislist = Db::table("cg_ti_list")->where(["id" => $formdata["dids"][$i]])->find();

                $tmp["cuser"] = Session::get("employee_id");
                $tmp["puser"] = Session::get("employee_id");
                $tmp["ctime"] = time();
                $tmp["ptime"] = time();
                $tmp["sn"] = $i + 1;
                $tmp["isVAT"] = $formdata["isdi"][$i];
                $tmp["ti_id"] = $thislist["ti_id"];
                $tmp["weishuihexiaojine"] = $formdata["weishui"][$i];
                $tmp["youwufapiao"] = $formdata["isfa"][$i];
                $tmp["fapiaohao"] = $formdata["fapiao"][$i];
                $tmp["shizengzhishui"] = $formdata["isdi"][$i];
                $tmp["shuilv"] = $formdata["shuilv"][$i];
                $tmp["shuijin"] = $tmp["weishuihexiaojine"] * $tmp["shuilv"] / 100;
                $tmp["hanshuihexiaojine"] = $tmp["weishuihexiaojine"] + $tmp["shuijin"];
                if($formdata["isdi"][$i])
                    $tmp["shijihexiaojine"] = $tmp["weishuihexiaojine"];
                else
                    $tmp["shijihexiaojine"] = $tmp["weishuihexiaojine"] + $tmp["shuijin"];
                $tmp["shijitourujine"] = $thislist["fb_shijitourufeiyong"];
                $tmp["huodongkaishiriqi"] = $thislist["start"];
                $tmp["zhifufangshi"] = $formdata["zfid"][$i];

                $tmp["beizhu"] = $formdata["beizhu"][$i];

                $tmp["hx_id"] = $res1;
                $tmp["list_id"] = $formdata["dids"][$i];


                if (in_array($tmp["list_id"], $buhelist)) {
                    $buyu_he = 1;
                } else {
                    $buyu_he = 0;
                }
                $tmp["yuebuhexiao"] = $buyu_he;

                $detail[] = $tmp;

                if ($thislist["hx_sqz"])
                    $updatalist["hx_sqz"] = $thislist["hx_sqz"] + $formdata["weishui"][$i];
                else
                    $updatalist["hx_sqz"] = $formdata["weishui"][$i];

                if ($thislist["hx_wsq"])
                    $updatalist["hx_wsq"] = $thislist["hx_wsq"] - $formdata["weishui"][$i];
                else
                    $updatalist["hx_wsq"] = $thislist["fb_shijiweishui"] - $formdata["weishui"][$i];
                if($thislist["hx_sqhs"]){
                    $updatalist["hx_sqhs"] =$thislist["hx_sqhs"]+ $formdata["weishui"][$i]*(1+$formdata["shuilv"][$i]/100);
                }else{
                    $updatalist["hx_sqhs"] = $formdata["weishui"][$i]*(1+$formdata["shuilv"][$i]/100);
                }
                if($formdata["isdi"][$i])
                    $hx_sj=$formdata["weishui"][$i];
                else
                    $hx_sj= $formdata["weishui"][$i]*(1+$formdata["shuilv"][$i]/100);
                if($thislist["hx_sqsj"]){
                    $updatalist["hx_sqsj"] =$thislist["hx_sqsj"]+ $hx_sj;
                }else{
                    $updatalist["hx_sqsj"] = $hx_sj;
                }
                if ($buyu_he) {
                    $updatalist["hx_status"] = 2;
                    $updatalist["hx_byhx"] = $updatalist["hx_wsq"];
                } else {
                    $updatalist["hx_status"] = 1;
                }
                Db::table("cg_ti_list")->where(["id" => $formdata["dids"][$i]])->update($updatalist);
            }
            //print_r($detail);exit;
            $res2 = Db::table("cg_ti_hexiao_list")->insertAll($detail);

            //$res3=Db::table("ti_apply")->where(["id"=>$aid])->update(["is_hexiao"=>1,"modifiled_on"=>date("Y-m-d H:i:s")]);

        } catch (\Exception $e) {
            //echo $e->getMessage();
            Db::rollBack();
            return json_encode(["msg" => "系统繁忙请稍后再试", "state" => 2]);
        }
        if ($res1 && $res2) {
            if($data["state"]==3){
                 $jieguo=$this->gowork(18,$res1);
                if($jieguo==json_encode(['state'=>1,'msg'=>'提交成功'])){
                    Db::commit();
                    return $jieguo;
                }else{
                    Db::rollBack();
                    return json_encode(["msg"=>"系统繁忙请稍后再试","state"=>2]);
                }
            }
            Db::commit();
            return json_encode(["msg" => "", "state" => 1]);


        } else {
            Db::rollBack();
            return json_encode(["msg" => "系统繁忙请稍后再试", "state" => 2]);
        }

    }

    //打印
    public function print_det($aid)
    {
         $apply = Db::table("cg_ti")->alias("ap")
            ->join("cg_ti yuan", "ap.old=yuan.id", "LEFT")
            ->join("cg_ti next", "ap.new=next.id", "LEFT")
            ->join("ti_state s", "ap.status=s.id")
            ->join("employee ec", "ap.cuser=ec.id", "LEFT")
            ->join("job_employee je", "ec.id=je.employee_id", "LEFT")
            ->join("job j", "je.job_id=j.id", "LEFT")
            ->join("department_employee de", "ec.id=de.employee_id", "LEFT")
            ->join("department d", "de.department_id=d.id", "LEFT")
            ->join("cg_jxs jx", "ap.jxs_id=jx.id")
            ->join("cg_market_zoning jz", "jx.zoning=jz.id", "LEFT")
            ->join("cg_market_provice jp", "jx.provice=jp.id", "LEFT")
            ->join("cg_market_city jc", "jx.city=jc.id", "LEFT")
            ->where(["ap.id" => $aid, "de.index" => 1])
            ->field("ap.title,ap.sn as no,yuan.sn as yuanno,next.sn as nextno,yuan.id as yuanid,next.id as nextid,s.title as zhuangtai,ec.em_name as cname,j.job_name,d.de_name,ap.ctime as created_on,jx.title as jingxiao,jz.title as fenqu,jp.title as sheng,jc.title as shi,yuan.status2 as yuantag,ap.status2 as nowtag,ap.status2 as tag,ap.fb is_fankui,ap.status,jx.id as jxs_id")
            ->find();
        $apply["created_on"] = date("Y-m-d", $apply["created_on"]);
       
        $fb = Db::table("all_ti_feeback_list")->where("apply_id=$aid and type=0 and is_deleted=0 and is_actived=1 and state not in (8,9)")->find();
        $hx = Db::table("cg_ti_hexiao")->alias("h")->join("cg_ti_hexiao_list hl", "hl.hx_id=h.id")->where("hl.ti_id=$aid and status not in (8,9)")->group("h.id")->field("h.id,h.sn")->select();
        $flagfb = 0;
        if ($fb)
            $flagfb = 1;
        $flaghx = 0;
        if ($hx)
            $flaghx = 1;
       
        $applynet = Db::table("cg_ti")->query("select apd.net_id,sum(apd.boxnum) as sellnums,sum(apd.bucha) as buchas,sum(apd.amount) as zonges,sum(apd.pizhunweishui) as pifuzonges,sum(fb_shijiweishui) as fankuijines,sum(apd.pizhunhanshui) as hanshuis,sum(apd.fb_hanshui) as fankuihanshuis,sum(fb_shijitourufeiyong) as fb_shijitourufeiyongs,sum(yjsjtrfy) as yjsjtrfys,sum(apd.totalExpectedSales) as xiaoshoues,sum(fb_boxnum) as fannums,sum(apd.fb_shijixiaoliang) as fanxiaoshoues,(sum(fb_boxnum)/sum(apd.boxnum)*100) as dachenglv,sum(apd.hx_yihexiao) as hexiaos,sum((apd.yuan_price-apd.now_price)*p.box_num*apd.bucha) as jxscha,sum((apd.wangdian_yuan-apd.wangdian_price)*p.box_num*apd.bucha) as netcha,sum(apd.hanshui*apd.yujiroi)/sum(apd.hanshui) as yujirois from cg_ti as ap inner join cg_ti_list as apd on apd.ti_id=ap.id inner join pro_products as p on apd.product=p.id where ap.id=$aid  group by apd.net_id");
          $all = ["sellnums" => 0, "xiaoshoues" => 0, "buchas" => 0, "zonges" => 0, "hanshuis" => 0,"jxscha"=>0,"netcha"=>0,"feiyonglv"=>0,"yujirois"=>0,"fannums"=>0,
            "fanxiaoshoues"=>0,"hexiaos"=>0,"pifuzonges"=>0,"fankuijines"=>0,"fankuihanshuis"=>0,"yjsjtrfys"=>0,"fb_shijitourufeiyongs"=>0
          ];
            for ($i = 0; $i < count($applynet); $i++) {
                $all["sellnums"] += $applynet[$i]["sellnums"];
                $all["xiaoshoues"] += $applynet[$i]["xiaoshoues"];
                $all["buchas"] += $applynet[$i]["buchas"];
                $all["zonges"] += $applynet[$i]["zonges"];
                $all["hanshuis"] += $applynet[$i]["hanshuis"];
                $all["jxscha"]+=$applynet[$i]["jxscha"];
                $all["netcha"]+=$applynet[$i]["netcha"];
                $applynet[$i]["feiyonglv"]=$applynet[$i]["hanshuis"]/$applynet[$i]["xiaoshoues"]*100;
                $all["yujirois"]=$all["hanshuis"]*$applynet[$i]["yujirois"];
                $all["fannums"]+=$applynet[$i]["fannums"];
                $all["fanxiaoshoues"]+=$applynet[$i]["fanxiaoshoues"];
                $all["hexiaos"]+=$applynet[$i]["hexiaos"];
                 $all["pifuzonges"] += $applynet[$i]["pifuzonges"];
                  $all["fankuijines"] += $applynet[$i]["fankuijines"];
                  $all["fankuihanshuis"] += $applynet[$i]["fankuihanshuis"];
                  if($applynet[$i]["yjsjtrfys"])
                    $all["yjsjtrfys"] += $applynet[$i]["yjsjtrfys"];
                if($applynet[$i]["fb_shijitourufeiyongs"])
                    $all["fb_shijitourufeiyongs"] += $applynet[$i]["fb_shijitourufeiyongs"];
            }
            $all["feiyonglv"]=$all["hanshuis"]/$all["xiaoshoues"]*100;
            $all["yujirois"]=$all["yujirois"]/$all["hanshuis"];
            $all["dachenglv"]=$all["fannums"]/ $all["sellnums"]*100;
           
        $net_num = count($applynet);
       

        $applyde = Db::table("cg_ti")->alias("ap")
            ->join("cg_ti_list apd", "apd.ti_id=ap.id")
            ->join("cg_ti_list yuanapd", "apd.refer_id=yuanapd.id", "LEFT")
            ->join("cg_net n", "apd.net_id=n.id", "LEFT")
            ->join("cg_system s", "n.system_id=s.id", "LEFT")
            ->join("pro_products p", "apd.product=p.id")
            ->join("pro_sku sk", "p.sku_id=sk.id")
            ->join("pro_series ps", "sk.series_id=ps.id")
            ->join("pro_price pp", "pp.pid=p.id")
            ->join("cg_feiyongkemu3 f3", "apd.feetype=f3.id")
            ->join("cg_paymethod cp", "apd.paymethod=cp.id")
            ->join("cg_fijiru cf", "apd.project=cf.id")
            ->join("cg_fijiruzd fj", "apd.jrbm=fj.id")->join("department d", "fj.title=d.id")
            ->where(["ap.id" => $aid])->order("apd.net_id,apd.product")
            ->field("ap.sn as no,apd.sn as detail_no,apd.net_id,apd.id as did,apd.is_bu,n.title as net,s.title as xitong,ps.series_name,p.pro_name,apd.start as start_time,apd.end as end_time,apd.expCanTime as  hexiao_time,apd.boxnum as sell_num,apd.bucha,p.unit,p.box_num,pp.factory,apd.yuan_price,apd.now_price,apd.wangdian_price,apd.lingshou_price,apd.huodong_price,f3.title as feiyong3,apd.amount as zonge,(apd.pizhunhanshui) as hanshui,apd.brief as beizhu,apd.head as fuzeren,cp.title as zffs,cf.title as jrfa,(apd.totalExpectedSales) as xiaoshoue,apd.feiyongmiaoshu as remark,d.de_name,apd.shuilv,apd.fb_shuilv,apd.isVAT as dikou,apd.fb_isVAT as dikou1,apd.zhejia,apd.hx_yihexiao as hexiao,apd.paymethod as zfid,apd.status as tag,yuanapd.start  as yuanstart,yuanapd.end as yuanend,yuanapd.expCanTime as yuanhexiao,apd.ydreason,apd.cancel_reason,apd.fb_shijixiaoliang as fankuinum,(apd.fb_shijixiaoliang) as shijixiaoshoue,(apd.fb_boxnum/apd.boxnum)*100 as xiaoliang,(apd.wangdian_price*apd.zhejia/100) as zj,(apd.wangdian_price-apd.wangdian_price*apd.zhejia/100) as wangcuxiao,(apd.wangdian_price*apd.zhejia/100)*p.box_num*apd.fb_shijixiaoliang as zjzj,yuanapd.yjsjtrfy  as yuanzonge,apd.pizhunweishui as  pifuzonge,apd.fb_shijiweishui as fankuijine,apd.fb_hanshui as fankuihanshui,apd.fb_shijitourufeiyong,apd.yjsjtrfy,apd.yujifeiyonglv,apd.jizhunboxnum as totalBenchmarkSales,apd.yujiroi,apd.zhejia,apd.wangdian_zhejia,((apd.yuan_price-apd.now_price)*p.box_num*apd.bucha) as jxscha,apd.maoli,apd.wangdian_yuan,((apd.wangdian_yuan-apd.wangdian_price)*p.box_num*apd.bucha) as netcha,apd.netout,apd.huodongout,apd.fb_boxnum")
            ->select();

        for ($i = 0; $i < count($applyde); $i++) {
            $applyde[$i]["start_time"] = date("Y-m-d", $applyde[$i]["start_time"]);
            $applyde[$i]["end_time"] = date("Y-m-d", $applyde[$i]["end_time"]);
            $applyde[$i]["hexiao_time"] = date("Y-m-d", $applyde[$i]["hexiao_time"]);
            if ($applyde[$i]["yuanstart"])
                $applyde[$i]["yuanstart"] = date("Y-m-d", $applyde[$i]["yuanstart"]);
            if ($applyde[$i]["yuanend"])
                $applyde[$i]["yuanend"] = date("Y-m-d", $applyde[$i]["yuanend"]);
            if ($applyde[$i]["yuanhexiao"])
                $applyde[$i]["yuanhexiao"] = date("Y-m-d", $applyde[$i]["yuanhexiao"]);
        }
        

        //费用支付方式
        $fipay = db('cg_paymethod')->field('id,title')->select();
       
        //费用类型
        $feiyongjine=Db::table("cg_ti")->alias("ap")
            ->join("cg_ti_list apd", "apd.ti_id=ap.id")
            ->join("cg_feiyongkemu3 f3", "apd.feetype=f3.id")
            ->where(["ap.id" => $aid])
            ->group("f3.id,apd.feetype")
            ->field("f3.title,sum(apd.pizhunhanshui) as jine")
            ->select();
        
        $logs=$this->getlog($aid);
        
        //excel
        $eid = Session::get("employee_id");
        $users = Db::table("employee")->where(["id" => $eid])->find();

        Vendor("PHPExcel");


        Vendor("PHPExcel.Writer.Excel5");

        // Loader::import('PHPExcel.Classes.PHPExcel');
        //Loader::import('PHPExcel.Classes.PHPExcel.IOFactory.PHPExcel_IOFactory');
        //  Vendor("Excel.PHPExcel.Writer.Excel2007");
        $objPHPExcel = new PHPExcel();


        $objProps = $objPHPExcel->getProperties();

        $objProps->setCreator('admin');
        $objProps->setLastModifiedBy('admin');
        $objProps->setTitle('Office 2003 XLSX Test Document');
        $objProps->setSubject('Office 2003 XLSX Test Document');
        $objProps->setDescription("Test document, generated by PHPExcel.");
        $objProps->setKeywords("office excel PHPExcel");
        $objProps->setCategory("Test");

        $objPHPExcel->setActiveSheetIndex(0);
        $objPHPExcel->getActiveSheet()->setTitle("常规促销申请");

        #################总标题

        $objPHPExcel->getActiveSheet()->getRowDimension('1')->setRowHeight(20);
        $objPHPExcel->getActiveSheet()->getRowDimension('2')->setRowHeight(20);
        $objPHPExcel->getActiveSheet()->getRowDimension('3')->setRowHeight(20);
        $objPHPExcel->getActiveSheet()->getRowDimension('4')->setRowHeight(30);
        $objPHPExcel->getActiveSheet()->mergeCells('A1:AW1');
        $objPHPExcel->getActiveSheet()->setCellValue('A1', "常规促销申请");
        //水平剧中
        $objPHPExcel->getActiveSheet()->getStyle('A1')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        //垂直剧中
        $objPHPExcel->getActiveSheet()->getStyle('A1')->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER);
        //加粗
        $objPHPExcel->getActiveSheet()->getStyle('A1')->getFont()->setBold(true);
        //字体
        $objPHPExcel->getActiveSheet()->getStyle('A1')->getFont()->setSize(14);
        #################表头信息
        $objPHPExcel->getActiveSheet()->mergeCells('A2:BH2');
        $objPHPExcel->getActiveSheet()->setCellValue('A2', "(本表单由软件导出，导出时间：" . date("Y-m-d H:i:s") . "；导出人：{$users["em_name"]})");
        //水平剧中
        $objPHPExcel->getActiveSheet()->getStyle('A2')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        //垂直剧中
        $objPHPExcel->getActiveSheet()->getStyle('A2')->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER);
        //加粗
        $objPHPExcel->getActiveSheet()->getStyle('A2')->getFont()->setBold(true);
        //字体
        $objPHPExcel->getActiveSheet()->getStyle('A2')->getFont()->setSize(14);
        #################申请标题
        $objPHPExcel->getActiveSheet()->mergeCells('A3:AW3');
        $objPHPExcel->getActiveSheet()->setCellValue('A3', $apply["title"]);
        //垂直剧中
        $objPHPExcel->getActiveSheet()->getStyle('A3')->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER);
        //加粗
        $objPHPExcel->getActiveSheet()->getStyle('A3')->getFont()->setBold(true);
        //字体
        $objPHPExcel->getActiveSheet()->getStyle('A3')->getFont()->setSize(11);

        ###################单据信息
        $objPHPExcel->getActiveSheet()->setCellValue('A4', "编号");
        $objPHPExcel->getActiveSheet()->setCellValueExplicit('B4', $apply["no"],PHPExcel_Cell_DataType::TYPE_STRING);
        $objPHPExcel->getActiveSheet()->mergeCells('B4:C4');
        $objPHPExcel->getActiveSheet()->setCellValue('D4', "原申请批复编号");
        if ($apply["yuanno"])
            $objPHPExcel->getActiveSheet()->setCellValueExplicit('E4', $apply["yuanno"],PHPExcel_Cell_DataType::TYPE_STRING);
        else
            $objPHPExcel->getActiveSheet()->setCellValue('E4', "无");
        $objPHPExcel->getActiveSheet()->mergeCells('E4:F4');
        $objPHPExcel->getActiveSheet()->setCellValue('G4', "修改后编号");
        if ($apply["nextno"])
            $objPHPExcel->getActiveSheet()->setCellValueExplicit('H4', $apply["nextno"],PHPExcel_Cell_DataType::TYPE_STRING);
        else
            $objPHPExcel->getActiveSheet()->setCellValue('H4', "无");
        $objPHPExcel->getActiveSheet()->mergeCells('H4:I4');
        $objPHPExcel->getActiveSheet()->setCellValue('J4', "申请时间");
        $objPHPExcel->getActiveSheet()->setCellValue('K4', $apply["created_on"]);
        $objPHPExcel->getActiveSheet()->mergeCells('K4:L4');
        $objPHPExcel->getActiveSheet()->setCellValue('M4', "申请人");
        $objPHPExcel->getActiveSheet()->setCellValue('N4', $apply["cname"] . "({$apply["job_name"]})");
        $objPHPExcel->getActiveSheet()->mergeCells('N4:O4');
        $objPHPExcel->getActiveSheet()->setCellValue('P4', "申请人部门");
        $objPHPExcel->getActiveSheet()->setCellValue('Q4', $apply["de_name"]);
        $objPHPExcel->getActiveSheet()->mergeCells('Q4:R4');
        $objPHPExcel->getActiveSheet()->setCellValue('S4', "状态");
        $zt = $apply["zhuangtai"];
        $fzt = "";
        if ($apply["tag"] == 1) {
            $fzt = "已异动";
        } else if ($apply["tag"] == 2) {
            $fzt = "已取消";
        } else {
            $fzt = "正常";
        }
        $objPHPExcel->getActiveSheet()->setCellValue('T4', "{$zt}/{$fzt}");
        $objPHPExcel->getActiveSheet()->mergeCells('T4:U4');
        $objPHPExcel->getActiveSheet()->mergeCells('V4:AW4');


        $objPHPExcel->getActiveSheet()->setCellValue('A5', "所属分区");
        $objPHPExcel->getActiveSheet()->setCellValue('B5', $apply["fenqu"]);
        $objPHPExcel->getActiveSheet()->mergeCells('B5:C5');
        $objPHPExcel->getActiveSheet()->setCellValue('D5', "所属省份");
        $objPHPExcel->getActiveSheet()->setCellValue('E5', $apply["sheng"]);
        $objPHPExcel->getActiveSheet()->mergeCells('E5:F5');
        $objPHPExcel->getActiveSheet()->setCellValue('G5', "所属城市");
        $objPHPExcel->getActiveSheet()->setCellValue('H5', $apply["shi"]);
        $objPHPExcel->getActiveSheet()->mergeCells('H5:I5');
        $objPHPExcel->getActiveSheet()->setCellValue('J5', "经销商名称");
        $objPHPExcel->getActiveSheet()->setCellValue('K5', $apply["jingxiao"]);
        $objPHPExcel->getActiveSheet()->mergeCells('K5:L5');
        //加粗
        $objPHPExcel->getActiveSheet()->getStyle('K5')->getFont()->setBold(true);
        $objPHPExcel->getActiveSheet()->setCellValue('M5', "性质");
        $objPHPExcel->getActiveSheet()->setCellValue('N5', "经销");
        $objPHPExcel->getActiveSheet()->mergeCells('N5:O5');
        $objPHPExcel->getActiveSheet()->mergeCells('P5:AW5');

        #########明细标题
         $objPHPExcel->getActiveSheet()->getStyle('6')->getAlignment()->setWrapText(true);
        
         $objPHPExcel->getActiveSheet()->getStyle('A6:AW6')->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID);
         $objPHPExcel->getActiveSheet()->getStyle('A6:AW6')->getFill()->getStartColor()->setARGB('0099CCFF');
             //水平剧中
         $objPHPExcel->getActiveSheet()->getStyle('A6:AW6')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
            //垂直剧中
         $objPHPExcel->getActiveSheet()->getStyle('A6:AW6')->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER);


        $objPHPExcel->getActiveSheet()->setCellValue('A6',"状态");
        $objPHPExcel->getActiveSheet()->setCellValue('B6',"序号");
        $objPHPExcel->getActiveSheet()->setCellValue('C6',"明细编号");
        $objPHPExcel->getActiveSheet()->setCellValue('D6',"系统名称");
        $objPHPExcel->getActiveSheet()->setCellValue('E6',"负责人");      
        $objPHPExcel->getActiveSheet()->setCellValue('F6',"网点名称");
        $objPHPExcel->getActiveSheet()->setCellValue('G6',"产品系列");
        $objPHPExcel->getActiveSheet()->setCellValue('H6',"促销产品");
        $objPHPExcel->getActiveSheet()->setCellValue('I6',"原促销执行时间");
        $objPHPExcel->getActiveSheet()->setCellValue('J6',"异动促销执行时间");
        $objPHPExcel->getActiveSheet()->setCellValue('K6',"预计核销时间");
        $objPHPExcel->getActiveSheet()->setCellValue('L6',"异动后核销时间");
        $objPHPExcel->getActiveSheet()->setCellValue('M6',"异动原因");
        $objPHPExcel->getActiveSheet()->setCellValue('N6',"取消原因");
        $objPHPExcel->getActiveSheet()->setCellValue('O6',"预计数量");
        $objPHPExcel->getActiveSheet()->setCellValue('P6',"预计销售额");
        $objPHPExcel->getActiveSheet()->setCellValue('Q6',"实际数量");
        $objPHPExcel->getActiveSheet()->setCellValue('R6',"实际销售额");
        $objPHPExcel->getActiveSheet()->setCellValue('S6',"销售达成率");
        $objPHPExcel->getActiveSheet()->setCellValue('T6',"需补差销售量");
        $objPHPExcel->getActiveSheet()->setCellValue('U6',"标准出厂价");
        $objPHPExcel->getActiveSheet()->setCellValue('V6',"经销商原供货价");
        $objPHPExcel->getActiveSheet()->setCellValue('W6',"经销商现供货价");
        $objPHPExcel->getActiveSheet()->setCellValue('X6',"经销商折价幅度");
        $objPHPExcel->getActiveSheet()->setCellValue('Y6',"总折价金额(元)");
        $objPHPExcel->getActiveSheet()->setCellValue('Z6',"经销商毛利率");

        $objPHPExcel->getActiveSheet()->setCellValue('AA6',"网点正常供货价");
        $objPHPExcel->getActiveSheet()->setCellValue('AB6',"网点促销供货价");
        $objPHPExcel->getActiveSheet()->setCellValue('AC6',"网点折价幅度");
        $objPHPExcel->getActiveSheet()->setCellValue('AD6',"总折价金额(元)");
        $objPHPExcel->getActiveSheet()->setCellValue('AE6',"原零售价");
        $objPHPExcel->getActiveSheet()->setCellValue('AF6',"活动期零售价");
        $objPHPExcel->getActiveSheet()->setCellValue('AG6',"已核销金额(元)");
        $objPHPExcel->getActiveSheet()->setCellValue('AH6',"费用名称");
        $objPHPExcel->getActiveSheet()->setCellValue('AI6',"异动前实际投入费用(元)");
        $objPHPExcel->getActiveSheet()->setCellValue('AJ6',"未税费用金额(元)(申请金额/批复金额/反馈金额)");
        $objPHPExcel->getActiveSheet()->setCellValue('AK6',"是否增值税(可抵扣)");
        $objPHPExcel->getActiveSheet()->setCellValue('AL6',"税率");
        $objPHPExcel->getActiveSheet()->setCellValue('AM6',"含税费用金额(元)");
        $objPHPExcel->getActiveSheet()->setCellValue('AN6',"实际投入费用(元)");
        $objPHPExcel->getActiveSheet()->setCellValue('AO6',"描述");
        $objPHPExcel->getActiveSheet()->setCellValue('AP6',"费用支付方式");
        $objPHPExcel->getActiveSheet()->setCellValue('AQ6',"费用小计(元)");
        $objPHPExcel->getActiveSheet()->setCellValue('AR6',"预计费用率");
        $objPHPExcel->getActiveSheet()->setCellValue('AS6',"基准销量");
        $objPHPExcel->getActiveSheet()->setCellValue('AT6',"预计ROI");
        $objPHPExcel->getActiveSheet()->setCellValue('AU6',"备注");
        $objPHPExcel->getActiveSheet()->setCellValue('AV6',"费用计入部门");
        $objPHPExcel->getActiveSheet()->setCellValue('AW6',"费用计入方案");

        $h=6;
        for($i=0;$i<count($applyde);$i++){
            $h++;$vo=$applyde[$i];
            $objPHPExcel->getActiveSheet()->getStyle($h)->getAlignment()->setWrapText(true);
              //水平剧中
            $objPHPExcel->getActiveSheet()->getStyle($h)->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
            //垂直剧中
            $objPHPExcel->getActiveSheet()->getStyle($h)->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER);
            if($vo["tag"]==0)
                $objPHPExcel->getActiveSheet()->setCellValueExplicit('A'.$h,"正常",PHPExcel_Cell_DataType::TYPE_STRING);
            else if($vo["tag"]==1)
                $objPHPExcel->getActiveSheet()->setCellValueExplicit('A'.$h,"异动",PHPExcel_Cell_DataType::TYPE_STRING);
            else
                $objPHPExcel->getActiveSheet()->setCellValueExplicit('A'.$h,"取消",PHPExcel_Cell_DataType::TYPE_STRING);
            $objPHPExcel->getActiveSheet()->setCellValueExplicit('B'.$h,$i+1,PHPExcel_Cell_DataType::TYPE_STRING);
            $objPHPExcel->getActiveSheet()->setCellValueExplicit('C'.$h,"{$vo["no"]}-{$vo["detail_no"]}",PHPExcel_Cell_DataType::TYPE_STRING);
            $objPHPExcel->getActiveSheet()->setCellValueExplicit('D'.$h,$vo["xitong"],PHPExcel_Cell_DataType::TYPE_STRING);
            $objPHPExcel->getActiveSheet()->setCellValueExplicit('E'.$h,$vo["fuzeren"],PHPExcel_Cell_DataType::TYPE_STRING);
            $objPHPExcel->getActiveSheet()->setCellValueExplicit('F'.$h,$vo["net"],PHPExcel_Cell_DataType::TYPE_STRING);
            $objPHPExcel->getActiveSheet()->setCellValueExplicit('G'.$h,$vo["series_name"],PHPExcel_Cell_DataType::TYPE_STRING);
            $objPHPExcel->getActiveSheet()->setCellValueExplicit('H'.$h,$vo["pro_name"],PHPExcel_Cell_DataType::TYPE_STRING);

            
            if($vo["tag"]==1){
                $objPHPExcel->getActiveSheet()->setCellValueExplicit('I'.$h,$vo["yuanstart"].'至'.$vo["yuanend"],PHPExcel_Cell_DataType::TYPE_STRING);
                $objPHPExcel->getActiveSheet()->setCellValueExplicit('J'.$h,$vo["start_time"].'至'.$vo["end_time"],PHPExcel_Cell_DataType::TYPE_STRING);
                $objPHPExcel->getActiveSheet()->setCellValueExplicit('K'.$h,$vo["yuanhexiao"],PHPExcel_Cell_DataType::TYPE_STRING);
                $objPHPExcel->getActiveSheet()->setCellValueExplicit('L'.$h,$vo["hexiao_time"],PHPExcel_Cell_DataType::TYPE_STRING);
            }else{
                $objPHPExcel->getActiveSheet()->setCellValueExplicit('I'.$h,$vo["start_time"].'至'.$vo["end_time"],PHPExcel_Cell_DataType::TYPE_STRING);
                $objPHPExcel->getActiveSheet()->setCellValueExplicit('K'.$h,$vo["hexiao_time"],PHPExcel_Cell_DataType::TYPE_STRING);
            }
            $objPHPExcel->getActiveSheet()->setCellValueExplicit('M'.$h,$vo["ydreason"],PHPExcel_Cell_DataType::TYPE_STRING);
            $objPHPExcel->getActiveSheet()->setCellValueExplicit('N'.$h,$vo["cancel_reason"],PHPExcel_Cell_DataType::TYPE_STRING);
            $objPHPExcel->getActiveSheet()->setCellValueExplicit('O'.$h,$vo["sell_num"],PHPExcel_Cell_DataType::TYPE_STRING);
            $objPHPExcel->getActiveSheet()->setCellValueExplicit('P'.$h,$vo["xiaoshoue"],PHPExcel_Cell_DataType::TYPE_STRING);
            $objPHPExcel->getActiveSheet()->setCellValueExplicit('Q'.$h,$vo["fb_boxnum"],PHPExcel_Cell_DataType::TYPE_STRING);
            $objPHPExcel->getActiveSheet()->setCellValueExplicit('R'.$h,$vo["shijixiaoshoue"],PHPExcel_Cell_DataType::TYPE_STRING);
            $objPHPExcel->getActiveSheet()->setCellValueExplicit('S'.$h,$vo["xiaoliang"].'%',PHPExcel_Cell_DataType::TYPE_STRING);
            $objPHPExcel->getActiveSheet()->setCellValueExplicit('T'.$h,$vo["bucha"],PHPExcel_Cell_DataType::TYPE_STRING);
            $objPHPExcel->getActiveSheet()->setCellValueExplicit('U'.$h,$vo["factory"].'元/'.$vo["unit"],PHPExcel_Cell_DataType::TYPE_STRING);
            $objPHPExcel->getActiveSheet()->setCellValueExplicit('V'.$h,$vo["yuan_price"].'元/'.$vo["unit"],PHPExcel_Cell_DataType::TYPE_STRING);
            $objPHPExcel->getActiveSheet()->setCellValueExplicit('W'.$h,$vo["now_price"].'元/'.$vo["unit"],PHPExcel_Cell_DataType::TYPE_STRING);
            $objPHPExcel->getActiveSheet()->setCellValueExplicit('X'.$h,$vo["zhejia"].'%',PHPExcel_Cell_DataType::TYPE_STRING);
            $objPHPExcel->getActiveSheet()->setCellValueExplicit('Y'.$h,round($vo["jxscha"],2),PHPExcel_Cell_DataType::TYPE_STRING);
            $objPHPExcel->getActiveSheet()->setCellValueExplicit('Z'.$h,$vo["maoli"].'%',PHPExcel_Cell_DataType::TYPE_STRING);
            $objPHPExcel->getActiveSheet()->setCellValueExplicit('AA'.$h,$vo["wangdian_yuan"].'元/'.$vo["unit"],PHPExcel_Cell_DataType::TYPE_STRING);
            $objPHPExcel->getActiveSheet()->setCellValueExplicit('AB'.$h,$vo["wangdian_price"].'元/'.$vo["unit"],PHPExcel_Cell_DataType::TYPE_STRING);
            $objPHPExcel->getActiveSheet()->setCellValueExplicit('AC'.$h,$vo["wangdian_zhejia"].'%',PHPExcel_Cell_DataType::TYPE_STRING);
            $objPHPExcel->getActiveSheet()->setCellValueExplicit('AD'.$h,round($vo["netcha"],2),PHPExcel_Cell_DataType::TYPE_STRING);
            $objPHPExcel->getActiveSheet()->setCellValueExplicit('AE'.$h,$vo["lingshou_price"].'元/'.$vo["unit"],PHPExcel_Cell_DataType::TYPE_STRING);
            $objPHPExcel->getActiveSheet()->setCellValueExplicit('AF'.$h,$vo["huodong_price"].'元/'.$vo["unit"],PHPExcel_Cell_DataType::TYPE_STRING);
            $objPHPExcel->getActiveSheet()->setCellValueExplicit('AG'.$h,round($vo["hexiao"],2),PHPExcel_Cell_DataType::TYPE_STRING);
            $objPHPExcel->getActiveSheet()->setCellValueExplicit('AH'.$h,$vo["feiyong3"],PHPExcel_Cell_DataType::TYPE_STRING);
            $objPHPExcel->getActiveSheet()->setCellValueExplicit('AI'.$h,round($vo["yuanzonge"],2),PHPExcel_Cell_DataType::TYPE_STRING);
            $objPHPExcel->getActiveSheet()->setCellValueExplicit('AJ'.$h,round($vo["zonge"],2).'/'.round($vo["pifuzonge"],2).'/'.round($vo["fankuijine"],2),PHPExcel_Cell_DataType::TYPE_STRING);
            if($vo["dikou1"]){
                $objPHPExcel->getActiveSheet()->setCellValueExplicit('AK'.$h,"可",PHPExcel_Cell_DataType::TYPE_STRING);
            }else{
                $objPHPExcel->getActiveSheet()->setCellValueExplicit('AK'.$h,"否",PHPExcel_Cell_DataType::TYPE_STRING);
            }
            if($vo["fb_shuilv"]){
                $objPHPExcel->getActiveSheet()->setCellValueExplicit('AL'.$h,$vo["fb_shuilv"].'%',PHPExcel_Cell_DataType::TYPE_STRING);
            }else{
                $objPHPExcel->getActiveSheet()->setCellValueExplicit('AL'.$h,$vo["shuilv"].'%',PHPExcel_Cell_DataType::TYPE_STRING);
            }
            if($vo["fankuihanshui"]){
                $objPHPExcel->getActiveSheet()->setCellValueExplicit('AM'.$h,round($vo["fankuihanshui"],2),PHPExcel_Cell_DataType::TYPE_STRING);
            }else{
                $objPHPExcel->getActiveSheet()->setCellValueExplicit('AM'.$h,round($vo["hanshui"],2),PHPExcel_Cell_DataType::TYPE_STRING);
            }
            if($vo["fb_shijitourufeiyong"]){
                $objPHPExcel->getActiveSheet()->setCellValueExplicit('AN'.$h,round($vo["fb_shijitourufeiyong"],2),PHPExcel_Cell_DataType::TYPE_STRING);
            }else{
                $objPHPExcel->getActiveSheet()->setCellValueExplicit('AN'.$h,round($vo["yjsjtrfy"],2),PHPExcel_Cell_DataType::TYPE_STRING);
            }
            $objPHPExcel->getActiveSheet()->setCellValueExplicit('AO'.$h,$vo["remark"],PHPExcel_Cell_DataType::TYPE_STRING);
            $objPHPExcel->getActiveSheet()->setCellValueExplicit('AP'.$h,$vo["zffs"],PHPExcel_Cell_DataType::TYPE_STRING);
            if($vo["fb_shijitourufeiyong"]){
                $objPHPExcel->getActiveSheet()->setCellValueExplicit('AQ'.$h,round($vo["fb_shijitourufeiyong"],2),PHPExcel_Cell_DataType::TYPE_STRING);
            }else{
                $objPHPExcel->getActiveSheet()->setCellValueExplicit('AQ'.$h,round($vo["yjsjtrfy"],2),PHPExcel_Cell_DataType::TYPE_STRING);
            }
            $objPHPExcel->getActiveSheet()->setCellValueExplicit('AR'.$h,$vo["yujifeiyonglv"].'%',PHPExcel_Cell_DataType::TYPE_STRING);
            $objPHPExcel->getActiveSheet()->setCellValueExplicit('AS'.$h,round($vo["totalBenchmarkSales"],2),PHPExcel_Cell_DataType::TYPE_STRING);
            $objPHPExcel->getActiveSheet()->setCellValueExplicit('AT'.$h,$vo["yujiroi"].'%',PHPExcel_Cell_DataType::TYPE_STRING);
            $objPHPExcel->getActiveSheet()->setCellValueExplicit('AU'.$h,$vo["beizhu"],PHPExcel_Cell_DataType::TYPE_STRING);
            $objPHPExcel->getActiveSheet()->setCellValueExplicit('AV'.$h,$vo["de_name"],PHPExcel_Cell_DataType::TYPE_STRING);
            $objPHPExcel->getActiveSheet()->setCellValueExplicit('AW'.$h,$vo["jrfa"],PHPExcel_Cell_DataType::TYPE_STRING);
        }
            $h++;
            #合计
            $objPHPExcel->getActiveSheet()->setCellValue('A'.$h,"总计");
            $objPHPExcel->getActiveSheet()->mergeCells("A{$h}:F{$h}");
             //水平剧中
            $objPHPExcel->getActiveSheet()->getStyle('A'.$h)->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_RIGHT);
            $objPHPExcel->getActiveSheet()->setCellValueExplicit('O'.$h,$all["sellnums"],PHPExcel_Cell_DataType::TYPE_STRING);
            $objPHPExcel->getActiveSheet()->setCellValueExplicit('P'.$h,$all["xiaoshoues"],PHPExcel_Cell_DataType::TYPE_STRING);
            $objPHPExcel->getActiveSheet()->setCellValueExplicit('Q'.$h,$all["fannums"],PHPExcel_Cell_DataType::TYPE_STRING);
            $objPHPExcel->getActiveSheet()->setCellValueExplicit('R'.$h,$all["fanxiaoshoues"],PHPExcel_Cell_DataType::TYPE_STRING);
            $objPHPExcel->getActiveSheet()->setCellValueExplicit('S'.$h,$all["dachenglv"].'%',PHPExcel_Cell_DataType::TYPE_STRING);
            $objPHPExcel->getActiveSheet()->setCellValueExplicit('T'.$h,$all["buchas"],PHPExcel_Cell_DataType::TYPE_STRING);
            $objPHPExcel->getActiveSheet()->setCellValueExplicit('Y'.$h,round($all["jxscha"],2),PHPExcel_Cell_DataType::TYPE_STRING);
            $objPHPExcel->getActiveSheet()->setCellValueExplicit('AD'.$h,round($all["netcha"],2),PHPExcel_Cell_DataType::TYPE_STRING);
            $objPHPExcel->getActiveSheet()->setCellValueExplicit('AG'.$h,round($all["hexiaos"],2),PHPExcel_Cell_DataType::TYPE_STRING);
            $objPHPExcel->getActiveSheet()->setCellValueExplicit('AJ'.$h,round($all["zonges"],2).'/'.round($all["pifuzonges"],2).'/'.round($all["fankuijines"],2),PHPExcel_Cell_DataType::TYPE_STRING);
            if($all["fankuihanshuis"]){
                $objPHPExcel->getActiveSheet()->setCellValueExplicit('AM'.$h,round($all["fankuihanshuis"],2),PHPExcel_Cell_DataType::TYPE_STRING);
            }else{
                $objPHPExcel->getActiveSheet()->setCellValueExplicit('AM'.$h,round($all["hanshuis"],2),PHPExcel_Cell_DataType::TYPE_STRING);
            }
            if($all["fb_shijitourufeiyongs"]){
                $objPHPExcel->getActiveSheet()->setCellValueExplicit('AN'.$h,round($all["fb_shijitourufeiyongs"],2),PHPExcel_Cell_DataType::TYPE_STRING);
            }else{
                $objPHPExcel->getActiveSheet()->setCellValueExplicit('AN'.$h,round($all["yjsjtrfys"],2),PHPExcel_Cell_DataType::TYPE_STRING);
            }
            if($all["fb_shijitourufeiyongs"]){
                $objPHPExcel->getActiveSheet()->setCellValueExplicit('AQ'.$h,round($all["fb_shijitourufeiyongs"],2),PHPExcel_Cell_DataType::TYPE_STRING);
            }else{
                $objPHPExcel->getActiveSheet()->setCellValueExplicit('AQ'.$h,round($all["yjsjtrfys"],2),PHPExcel_Cell_DataType::TYPE_STRING);
            }
            $objPHPExcel->getActiveSheet()->setCellValueExplicit('AR'.$h,round($all["feiyonglv"],2).'%',PHPExcel_Cell_DataType::TYPE_STRING);
            
            $objPHPExcel->getActiveSheet()->setCellValueExplicit('AT'.$h,round($all["yujirois"],2).'%',PHPExcel_Cell_DataType::TYPE_STRING);

            $h+=2;
             $objPHPExcel->getActiveSheet()->setCellValue('A'.$h,"审批意见");
        $objPHPExcel->getActiveSheet()->mergeCells("A{$h}:Y{$h}");
         $objPHPExcel->getActiveSheet()->getStyle("A{$h}")->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID);
        $objPHPExcel->getActiveSheet()->getStyle("A{$h}")->getFill()->getStartColor()->setARGB('0099CCFF');
        
         for($i=0;$i<count($logs);$i++){
            $h++;
            if($logs[$i]["COMMENTS"])
                $str="{$logs[$i]["USERNAME"]} 审批动作：{$logs[$i]["MEMO"]}；审批意见：{$logs[$i]["COMMENTS"]}(审批时间：{$logs[$i]["ACTIONTIME"]})";
            else
                $str="{$logs[$i]["USERNAME"]} 审批动作：{$logs[$i]["MEMO"]}；审批意见：无 (审批时间：{$logs[$i]["ACTIONTIME"]})";
             $objPHPExcel->getActiveSheet()->setCellValue('A'.$h,$str);
            $objPHPExcel->getActiveSheet()->mergeCells("A{$h}:AW{$h}");
        }
             $styleArray = array(  
        'borders' => array(  
            'allborders' => array(  
                //'style' => PHPExcel_Style_Border::BORDER_THICK,//边框是粗的  
                'style' => PHPExcel_Style_Border::BORDER_THIN,//细边框  
                //'color' => array('argb' => 'FFFF0000'),  
            ),  
        ),  
    );  
   $objPHPExcel->getActiveSheet()->getStyle('A1:AW'.$h)->applyFromArray($styleArray);//这里就是画出从单元格A5到N5的边框，看单元格最右边在哪哪
            //设置宽度
            $objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(15);
            $objPHPExcel->getActiveSheet()->getColumnDimension('B')->setWidth(15);
            $objPHPExcel->getActiveSheet()->getColumnDimension('C')->setWidth(15);
            $objPHPExcel->getActiveSheet()->getColumnDimension('D')->setWidth(20);
            $objPHPExcel->getActiveSheet()->getColumnDimension('E')->setWidth(30);
            $objPHPExcel->getActiveSheet()->getColumnDimension('F')->setWidth(15);
            $objPHPExcel->getActiveSheet()->getColumnDimension('G')->setWidth(15);
            $objPHPExcel->getActiveSheet()->getColumnDimension('H')->setWidth(15);
            $objPHPExcel->getActiveSheet()->getColumnDimension('I')->setWidth(30);
            $objPHPExcel->getActiveSheet()->getColumnDimension('J')->setWidth(15);
            $objPHPExcel->getActiveSheet()->getColumnDimension('K')->setWidth(30);
            $objPHPExcel->getActiveSheet()->getColumnDimension('L')->setWidth(15);
            $objPHPExcel->getActiveSheet()->getColumnDimension('M')->setWidth(15);
            $objPHPExcel->getActiveSheet()->getColumnDimension('N')->setWidth(15);
            $objPHPExcel->getActiveSheet()->getColumnDimension('O')->setWidth(40);
            $objPHPExcel->getActiveSheet()->getColumnDimension('P')->setWidth(15);
            $objPHPExcel->getActiveSheet()->getColumnDimension('Q')->setWidth(15);
            $objPHPExcel->getActiveSheet()->getColumnDimension('R')->setWidth(15);
            $objPHPExcel->getActiveSheet()->getColumnDimension('S')->setWidth(20);
            $objPHPExcel->getActiveSheet()->getColumnDimension('T')->setWidth(20);
            $objPHPExcel->getActiveSheet()->getColumnDimension('U')->setWidth(20);
            $objPHPExcel->getActiveSheet()->getColumnDimension('V')->setWidth(20);
            $objPHPExcel->getActiveSheet()->getColumnDimension('W')->setWidth(20);
            $objPHPExcel->getActiveSheet()->getColumnDimension('X')->setWidth(15);
            $objPHPExcel->getActiveSheet()->getColumnDimension('Y')->setWidth(15);
            $objPHPExcel->getActiveSheet()->getColumnDimension('Z')->setWidth(15);
            $objPHPExcel->getActiveSheet()->getColumnDimension('AA')->setWidth(15);
            $objPHPExcel->getActiveSheet()->getColumnDimension('AB')->setWidth(15);
            $objPHPExcel->getActiveSheet()->getColumnDimension('AC')->setWidth(15);
            $objPHPExcel->getActiveSheet()->getColumnDimension('AD')->setWidth(15);
            $objPHPExcel->getActiveSheet()->getColumnDimension('AE')->setWidth(15);
            $objPHPExcel->getActiveSheet()->getColumnDimension('AF')->setWidth(15);
            $objPHPExcel->getActiveSheet()->getColumnDimension('AG')->setWidth(15);
            $objPHPExcel->getActiveSheet()->getColumnDimension('AH')->setWidth(15);
            $objPHPExcel->getActiveSheet()->getColumnDimension('AI')->setWidth(15);
            $objPHPExcel->getActiveSheet()->getColumnDimension('AJ')->setWidth(15);
            $objPHPExcel->getActiveSheet()->getColumnDimension('AK')->setWidth(15);
            $objPHPExcel->getActiveSheet()->getColumnDimension('AL')->setWidth(15);
            $objPHPExcel->getActiveSheet()->getColumnDimension('AM')->setWidth(15);
            $objPHPExcel->getActiveSheet()->getColumnDimension('AN')->setWidth(15);
            $objPHPExcel->getActiveSheet()->getColumnDimension('AO')->setWidth(15);
            $objPHPExcel->getActiveSheet()->getColumnDimension('AP')->setWidth(15);
            $objPHPExcel->getActiveSheet()->getColumnDimension('AQ')->setWidth(15);
            $objPHPExcel->getActiveSheet()->getColumnDimension('AR')->setWidth(15);
            $objPHPExcel->getActiveSheet()->getColumnDimension('AS')->setWidth(30);
            $objPHPExcel->getActiveSheet()->getColumnDimension('AT')->setWidth(15);
            $objPHPExcel->getActiveSheet()->getColumnDimension('AU')->setWidth(15);
            $objPHPExcel->getActiveSheet()->getColumnDimension('AV')->setWidth(15);
            $objPHPExcel->getActiveSheet()->getColumnDimension('AW')->setWidth(15);

        
        $objWriter = new PHPExcel_Writer_Excel5($objPHPExcel);
        //var_dump($objWriter);exit;
        ob_end_clean();
        header("Pragma: public");
        header("Expires:0");
        header("Cache-Control:must-revalidate, post-check=0, pre-check=0");
        header("Content-Type:application/force-download");
        header("Content-Type:application/vnd.ms-execl");
        header("Content-Type:application/octet-stream");
        header("Content-Type:application/download");
        header('Content-Disposition:attachment;filename=完整版.xls');
        header("Content-type:text/html;charset=utf-8");
        header("Content-Transfer-Encoding:binary");
        $objWriter->save('php://output');
    }

    //查看流程图
    public function workflowchart()
    {
        $id = $this->request->param('id');
        $cate_id=db("cg_ti")->where(["id"=>$id])->value("cate_id");
        if($cate_id==1){
            $ywid=3;
        }else if($cate_id==2){
            $ywid=21;
        }else{
            $ywid=22;
        }

        $workId = db('cg_workflow')->where(['ywlx' => $ywid, 'yw_id' => $id])->value('workId');

        $trackId = db('cg_workflow')->where(['ywlx' => $ywid, 'yw_id' => $id])->value('trackId');
        //$arr=$workId = db('cg_workflow')->where(['ywlx' => $ywid, 'yw_id' => $id])->find();
        //print_r($arr);exit;
         header('location:'.config('workflow_url').'/workflow/module/workflow/flow.info.html?workId='.$workId.
            '&trackId='.$trackId);
    }
}
